zoukankan      html  css  js  c++  java
  • 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 
    ";
            pthread_exit(NULL);
            cout << "main return 
    ";
            return 0;
    }
    

    使用pthread_exit(NULL);, 输出结果如下:
    FnNqde.png

  • 相关阅读:
    Alpha 冲刺 (10/10)
    Alpha 冲刺 (9/10)
    Alpha 冲刺 (8/10)
    Alpha 冲刺 (7/10)
    Alpha 冲刺 (6/10)
    Alpha 冲刺 (5/10)
    18软工实践-团队现场编程实战(抽奖系统)
    Alpha 冲刺 (4/10)
    BETA(4)
    BETA(3)
  • 原文地址:https://www.cnblogs.com/willhua/p/10049812.html
Copyright © 2011-2022 走看看