C 当工作线程具有无限while循环时,为什么要分离工作线程?

C 当工作线程具有无限while循环时,为什么要分离工作线程?,c,multithreading,C,Multithreading,我不熟悉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) {

我不熟悉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.
    }
}
#定义第4行
int main(int argc,字符**argv){
...
对于(i=0;i

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

这将是清理线程或准备关闭进程的代码的一部分。由于该代码不存在,并且无法完全关闭任何东西,因此调用是否存在也没有区别。线程无论如何都不能终止或连接,因此它是否分离也没有什么区别。

这可能与软件开发中的许多事情类似-在这种情况下不严格需要,但为了完整性,最好这样做。这是关于以最好的方式做事。例如,如果有人更改
while
循环,使其具有一个退出点,则代码仍能正确运行。循环中的代码有几种方法可以跳出该循环。例如
goto
其中有一些
标签:
是在循环之外定义的。当图书馆有样板文件可供使用时,通常有一个很好的理由总是使用样板文件。