C++ 为什么pthread_exit的行为类似于pthread_join?
代码:C++ 为什么pthread_exit的行为类似于pthread_join?,c++,c,pthreads,pthread-join,pthread-exit,C++,C,Pthreads,Pthread Join,Pthread Exit,代码: void*PrintHello(void*threadid) { coutpthread\u exit()只终止调用线程。因此,当您从main()调用它时,它会终止主线程,同时允许进程继续。这是意料之中的 如果您调用exit()(或通过返回隐式退出),它将终止整个进程,您将看到printHello也将终止。pthread\u exit()仅终止调用线程。因此,当您从main()调用它时,它终止主线程,同时允许进程继续。这与预期的一样 如果您调用exit()(或通过返回隐式退出),它将终止
void*PrintHello(void*threadid)
{
coutpthread\u exit()
只终止调用线程。因此,当您从main()
调用它时,它会终止主线程,同时允许进程继续。这是意料之中的
如果您调用exit()
(或通过返回隐式退出),它将终止整个进程,您将看到printHello
也将终止。pthread\u exit()
仅终止调用线程。因此,当您从main()调用它时
,它终止主线程,同时允许进程继续。这与预期的一样
如果您调用exit()
(或通过返回隐式退出),它将终止整个过程,您将看到printHello
也被终止。有一个很好的资源,但请引用解释问题的部分:
关于从main()调用pthread_exit()的讨论:
- 如果不显式调用pthread_exit(),则如果main()在其生成的线程之前完成,则肯定会出现问题。它创建的所有线程都将终止,因为main()已完成且不再存在以支持线程
- 通过让main()像最后一件事一样显式调用pthread_exit(),main()将阻塞并保持活动状态,以支持它创建的线程,直到它们完成为止
这是一个很好的资源,但引用解释您问题的部分:
关于从main()调用pthread_exit()的讨论:
- 如果不显式调用pthread_exit(),则如果main()在其生成的线程之前完成,则肯定会出现问题。它创建的所有线程都将终止,因为main()已完成且不再存在以支持线程
- 通过让main()像最后一件事一样显式调用pthread_exit(),main()将阻塞并保持活动状态,以支持它创建的线程,直到它们完成为止
void *PrintHello(void *threadid)
{
cout<<"Hello"<<endl;
sleep(3);
cout<<"Still PrintHello is alive"<<endl;
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
cout<<"Calling thread:"<<t<<endl;
pthread_create(&threads[0], NULL, PrintHello, NULL);
//pthread_join(threads[0],NULL);
cout<<"Main exits"<<endl;
pthread_exit(NULL);
}