• linux下主线程return 0和pthread_exit(NULL)的区别


    1.当linux和Windows中,主线程以return 0结束时,程序会在主线程运行完毕后结束.
    2.当linux中,主线程以pthread_exit(NULL)作为返回值,则主线程会等待子线程.


    #include<stdio.h> #include<unistd.h> #include<pthread.h> void * task(void * param) { sleep(50); printf("hello "); pthread_exit(NULL); } int main() { //初始化线程 pthread_t tid; pthread_attr_t attr; //有啥用啊 pthread_attr_init(&attr); //创建线程 int rc = pthread_create(&tid, &attr, task, NULL); if(rc) { printf("线程创建失败! "); return -1; } printf("创建主线程 "); pthread_exit(NULL); //return 0; }

    上面的代码在linux下执行,运行结果为:

    创建主线程
    hello

    运行现象: 没有指定去等待子线程,主线程也会等待子线程执行完毕后,才会最后结束程序.

    但当把 main函数中改为如下这种:发现打印结果也只是:  创建主线程

        //pthread_exit(NULL);
        return 0;

    类似的在windows下,主线程中return 0,则主线程结束后就会马上结束程序.

    #include <iostream>
    #include "windows.h"
    #include "stdlib.h"
    
    using namespace std;
    DWORD WINAPI ThreadFun(void * param)
    {
        Sleep(5000);
        cout << "子线程" << endl;
        return 0;
    }
    
    int main()
    {
        //创建子线程
        HANDLE h;
        DWORD ThreadID;
        h= CreateThread(0, 0, ThreadFun, NULL, 0, &ThreadID);
    
        cout << "主线程执行完毕" << endl;
        return 0;
    }
    执行结果:

    主线程执行完毕
    新战场:https://blog.csdn.net/Stephen___Qin
  • 相关阅读:
    Spring学习(一)初识Spring
    搜索引擎学习(七)解析查询
    搜索引擎学习(六)Query的子类查询
    Oracle学习(十四)分表分区
    Oracle学习(十三)优化专题
    Python学习————流程控制之while循环
    Python学习————深浅copy
    Python学习————while循环作业
    Python学习————运算符
    Python学习————与用户交互
  • 原文地址:https://www.cnblogs.com/Stephen-Qin/p/12730670.html
Copyright © 2020-2023  润新知