线程创建(独立)永远不会执行 [英] Thread created (detached) never executed
本文介绍了线程创建(独立)永远不会执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了这个code:
void* th (void* arg)
{
sleep(1);
for(int i=0; i<1000;i++)
{
fprintf(stderr,"%d\t",i);
}
pthread_exit(NULL);
}
int main(int argc, char** argv)
{
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
pthread_create(&thread,&attr,th,NULL);
pthread_attr_destroy(&attr);
return 0;
}
分离状态的应使线程没有可连接,所以它应该运行甚至在主要流程是terminated.But未打印的数字,我看到的是该线程终止而没有任何打印到标准错误。
为什么不分离的线程中执行?
The detach state should make the thread not joinable, so it should run even after the main process is terminated.But it doesn't print the numbers, all I see is that the thread terminated without printing anything to stderr.
Why isn't the detached thread executed?
推荐答案
A 收益
从主
线程相当于整个过程的退出
,所以你的过程将退出之前,你的线程甚至会打印出任何东西。使用了pthread_exit
,而不是终止该线程。
A return
from the main
thread is equivalent to an exit
of the whole process, so your process will exit before your thread may even print anything. Use pthread_exit
instead to terminate that thread.
这篇关于线程创建(独立)永远不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文