码迷,mamicode.com
首页 > 编程语言 > 详细

pthread_exit在main线程中的用处

时间:2018-12-01 17:12:30      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:pac   when   create   out   用处   win   red   ack   iostream   

在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);, 输出结果如下:
技术分享图片

pthread_exit在main线程中的用处

标签:pac   when   create   out   用处   win   red   ack   iostream   

原文地址:https://www.cnblogs.com/willhua/p/10049812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!