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也會隨着退出。

FnNLIH.png

#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);, 輸出結果如下:
FnNqde.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM