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

标签 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;
}

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

看来主线程不应该是pthread,也不应该是pthread!如果我不放置它,代码将无法运行:代码编译并执行,但我只得到“起始线程”打印消息,而不是“hello from ...”消息。

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

此外,如果我注释掉 include <psthread.h>,代码将正确编译和执行。 .

最佳答案

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

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

来自 pthread_exit 手册页:

The process will exit with an exit status of 0 after the last thread has been terminated. The behavior is as if the implementation called exit() with a zero argument at thread termination time.

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

关于c++ - 为什么我需要从主线程使用 `pthread_exit()`,而它不是由 `pthread_create` 创建的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5313528/

相关文章:

c - Linux POSIX C 动态字符串数组问题

c++ - 如何使用 C/C++ 在 exe 中完全内部存储用户设置?

c++ - 数据压缩器需要哪些数学知识?

sockets - 获取一个随机的、仍然可用的高端口号

Excel posix时间

c - POSIX 名称信号量在进程退出后不释放

c - 使用 posix 函数显示所有进程

c++ - `typename = enable_if_t<...>` 和 `enable_if_t<...,bool> = true` 之间的区别

c++ - 如何在visual studio 2008中设置数据写入断点

表达式中的 C++ 运算符重载