在main線程中調用 會起到只讓main線程退出,但是保留進程資源,供其他由main創建的線程使用,直至所有線程都結束,但在其他線程中不會有這種效果 "https://stackoverflow.com/questions/3559463/is it ok to call pthread exit ...
在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 \n";
pthread_exit(NULL);
cout << "main return \n";
return 0;
}
使用pthread_exit(NULL);
, 輸出結果如下: