c - 当工作线程具有无限的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循环,所以不需要自动收割自己,因为它永远不会停止?
解决方案
这将是清理线程或准备关闭进程的代码的一部分。由于该代码不存在并且没有办法干净地关闭任何东西,因此调用是否存在没有区别。无论如何,线程永远不会终止或加入,因此无论它是否分离都没有区别。
推荐阅读
- javascript - 错误类型错误:无法读取未定义的属性“ngInjectableDef”
- bluetooth-lowenergy - 你知道如何在手机上编写 BLE5 功能吗?
- json - 如何在jmeter中断言json对象?
- nativescript - ObservableArray 上的拼接导致崩溃
- java - 406 HttpMediaTypeNotAcceptableException:找不到“文本/日历”类型输出的可接受表示
- php - 索引在 php 的 foreach 循环中不保持固定
- java - Spring Security 5.1 - 使用 WebClient 获取客户端凭证流的令牌
- python - 从许多 csv 文件中选择行并创建新文件
- amazon-web-services - 仅允许 ECR 请求的安全组出口规则
- sql - 访问:使用分组条件查询