简体   繁体   中英

Kill either thread and exit process

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;
}

一种方法是声明一个原子整数(最初设置为 0),两个线程都可以访问(例如,使其成为全局,或给两个线程一个指向它的指针,或其他),并让每个线程定期读取它的value 并在值为 1 时退出。然后让每个线程在线程退出时将 atomic int 的值设置为 1,以通知另一个线程也退出。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM