为什么我需要从主线程使用“pthread_exit()”,而它不是由“pthread_create”创建的?

cro*_*ant 4 c++ posix

我对我正在测试以开始理解 posix 线程的一些代码有疑问。

我有这个基本代码:

#include <iostream>
#include <string>
#include <sstream>
#include <pthread.h>

using namespace std;

void *printInfo(void *thid){
    long tid;
    tid =(long)thid;
    printf("Hello from thread %ld.\n",tid);
    pthread_exit(NULL);
}

int main (int argc, char const *argv[])
{
    int num =8;
    pthread_t threadlist[num];
    int rc;
    long t;
    for(t=0;t<num;t++){
        printf("Starting thread %ld\n",t);
        rc = pthread_create(&threadlist[t],NULL,printInfo,(void *)t);
        if(rc)
        {
            printf("Error creating thread");
            exit(-1);
            
        }
    }
    pthread_exit(NULL);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

非常简单的代码,启动线程并从中打印,这一切都很神奇,除了我不明白主方法末尾之前的pthread_exit(NULL)最后一个。return 0;

看来主线程不应该是pthread,也不应该需要它!如果我不添加它,代码将不起作用:代码编译并执行,但我只收到“启动线程”打印消息,而不是“hello from ...”消息。

所以基本上我想知道为什么需要这样做。

另外,如果我注释掉 include ,代码就会正确编译和执行<psthread.h>

小智 5

如果您不在 main 函数中使用 pthread_exit ,那么所有创建的线程都会在 main 完成时终止,即在您的情况下,在它们打印任何内容之前。

通过在 main 函数中调用 pthread_exit 使 main 等待,直到所有线程完成。

从 pthread_exit 手册页:

最后一个线程终止后,进程将以退出状态 0 退出。该行为就像在线程终止时调用 exit() 且参数为零的实现一样。

这是指从主进程线程调用 pthread_exit() 。