欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

pthread_exit在main线程中的用处

程序员文章站 2022-06-05 21:06:22
在main线程中调用 会起到只让main线程退出,但是保留进程资源,供其他由main创建的线程使用,直至所有线程都结束,但在其他线程中不会有这种效果 "https://*.com/questions/3559463/is it ok to call pthread exit ......

在main线程中调用pthread_exit会起到只让main线程退出,但是保留进程资源,供其他由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也会随着退出。

pthread_exit在main线程中的用处

#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);, 输出结果如下:
pthread_exit在main线程中的用处