0

I am creating two threads that run independently. When there is an error in one of the threads, I return from that particular thread with return value -1. But I want to kill the other thread and gracefully terminate/ exit the process. How do I achieve this?

pthread_t thr1, thr2;

void *func1(void *args)
{
  while(1){
     .....
     if(/*error*/) {
         return (void *)-1;
     }
  }
  return (void *)0;

}

void *func2(void *args)
{
  while(1){
    .....
    if(/*error*/) {
       return (void *)-1;
    }
  }
  return (void *)0;

}

int main(){

....

    if(pthread_create(&thr1, NULL, func1, NULL) != 0) {
        return -1;
    }

    if(pthread_create(&thr2, NULL, func2, NULL) != 0) {
        return -1;
    }

    /* If all goes well, do pthread_join for both threads, 
    but if I return error, i.e. -1 from thread functions, 
    how do I kill the other and exit the process? */

    (void)pthread_join(thr1, NULL);
    (void)pthread_join(thr2, NULL);

    return 0;
}
Shubham
  • 628
  • 1
  • 9
  • 19
bvj0412
  • 17
  • 5
  • Once you _kill_ a thread, nothing is graceful anymore. https://devblogs.microsoft.com/oldnewthing/20150814-00/?p=91811 - You better signal the thread somehow that it should exit by itself. – CherryDT Oct 20 '21 at 00:30
  • Some of the answers in [here](https://stackoverflow.com/questions/6836894/terminating-a-thread-in-c) might help. – sj95126 Oct 20 '21 at 00:31
  • Why not just call your OS 'TerminateProcess()' API, eg. via abort()? 'Graceful exit' by user code is not desirable in most cases, (on a non-trivial OS, anyway) - at best, it is an albatross round your neck that gets heavier as you develop your app and have to continually retest shutdown code. At worst, it is actually impossible because some thread is looping/blocked in opaque library code. – Martin James Oct 20 '21 at 04:23

1 Answers1

1

One way to do it would be to declare an atomic int (initially set to 0) that both threads have access to (e.g. make it a global, or give both threads a pointer to it, or whatever) and have each thread periodically read its value and exit if the value is 1. Then have each thread set the atomic int's value to one when the thread exits, to notify the other thread to also exit.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234