我是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循环,所以它没有必要自动收割,因为它永远不会停止?
这将是清理线程或准备关闭进程的代码的一部分。由于该代码不存在,也没有办法干净地关闭任何东西,因此无论调用是否存在都没有区别。线程无论如何都不能终止或连接,所以它是否分离没有什么区别。