【问题标题】:Kill either thread and exit process杀死任一线程并退出进程
【发布时间】:2021-12-06 20:37:18
【问题描述】:

我正在创建两个独立运行的线程。当其中一个线程出现错误时,我会从该特定线程返回并返回值 -1。但我想杀死另一个线程并优雅地终止/退出进程。我如何做到这一点?

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

【问题讨论】:

  • 一旦你杀死一个线程,就没有什么是优雅的了。 devblogs.microsoft.com/oldnewthing/20150814-00/?p=91811 - 你最好以某种方式通知线程它应该自行退出。
  • here 中的一些答案可能会有所帮助。
  • 为什么不直接调用操作系统的“TerminateProcess()”API,例如。通过中止()?在大多数情况下,用户代码的“优雅退出”是不可取的,(无论如何,在一个非平凡的操作系统上) - 充其量,它是你脖子上的信天翁,随着你开发你的应用程序变得越来越重,并且必须不断重新测试关闭代码.在最坏的情况下,实际上是不可能的,因为某些线程在不透明的库代码中循环/阻塞。

标签: c multithreading pthreads pthread-join


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-07-27
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多