pthread_exit在main线程中的用处
Posted willhua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pthread_exit在main线程中的用处相关的知识,希望对你有一定的参考价值。
在main线程中调用pthread_exit
会起到只让main线程退出,但是保留进程资源,供其他由main创建的线程使用,直至所有线程都结束,但在其他线程中不会有这种效果
https://stackoverflow.com/questions/3559463/is-it-ok-to-call-pthread-exit-from-main
To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).
It‘s fine to use pthread_exit in main. When pthread_exit is used, the main thread will stop executing and will remain in zombie(defunct) status until all other threads exit.
If you are using pthread_exit in main thread, cannot get return status of other threads and cannot do clean-up for other threads (could be done using pthread_join(3)). Also, it‘s better to detach threads(pthread_detach(3)) so that thread resources are automatically released on thread termination. The shared resources will not be released until all threads exit.
在win10的wls中,使用g++ -g -pthread pthreadtest.cpp
编译如下代码,然后执行,会发现main退出之后,pthread1和pthread2还是会继续跑。而,如果在mian中,注释pthread_exit(NULL);
,使用return退出,则pthread1和pthread2也会随着退出。
#include <pthread.h>
#include <iostream>
#include <unistd.h>
using namespace std;
//int a = 1, b = 2;
void * fun(void * param){
int *ptr = (int *)param;
while(true){
cout <<"from pthread " << (*ptr) << endl;
sleep(2);
}
return NULL;
}
int main(){
int a = 1, b = 2;
pthread_t t1, t2;
pthread_create(&t1, NULL, fun, &a);
pthread_create(&t2, NULL, fun, &b);
int c = 10;
while(--c > 0){
cout << "from main " << c << endl;
sleep(1);
}
cout << "main pthread_exit
";
pthread_exit(NULL);
cout << "main return
";
return 0;
}
使用pthread_exit(NULL);
, 输出结果如下:
以上是关于pthread_exit在main线程中的用处的主要内容,如果未能解决你的问题,请参考以下文章
终止线程执行的3种方法(pthread_exit()pthread_cancel()return)