当前位置: 移动技术网 > 科技>操作系统>Linux > pthread_exit在main线程中的用处

pthread_exit在main线程中的用处

2018年12月02日  | 移动技术网科技  | 我要评论

在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也会随着退出。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网