首页 > 解决方案 > 当工作线程具有无限的while循环时,为什么要分离工作线程?

问题描述

我是 C 和多线程编程的新手,只是关于分离线程的一些问题。以下是我教科书中的一些示例代码:

#define NTHREADS 4

int main(int argc, char **argv) {
   ...
   for (i = 0; i < NTHREADS; i++)          /* Create worker threads */
      pthread_create(&tid, NULL, thread, NULL);
   while (1) {
      ...// main thread produce repeatedly produces new items and inserts them in a shared buffer that will be consumed by the worker threads
   }
}

void *thread(void *vargp) {
    pthread_detach(pthread_self());
    while (1) {
        ...// worker thread consumes the item from the shared buffer.
    }
}

我的问题是,为什么工作线程需要调用pthread_detach(pthread_self());?因为下面有一个无限的while循环,所以不需要自动收割自己,因为它永远不会停止?

标签: cmultithreading

解决方案


这将是清理线程或准备关闭进程的代码的一部分。由于该代码不存在并且没有办法干净地关闭任何东西,因此调用是否存在没有区别。无论如何,线程永远不会终止或加入,因此无论它是否分离都没有区别。


推荐阅读