Posix线程基本问题C ++

时间:2011-03-15 14:52:10

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

非常简单的代码,启动线程并从它们打印,除了我不理解返回0之前的最后一个pthread_exit(NULL)之外,所有的工作都很奇怪;在主要方法的最后。

似乎主线程不应该是pthread,并且不应该需要它! 如果我没有把它,代码不起作用(意思是代码编译,并执行,但我只得到“开始线程”打印消息,而不是“hello from ...”消息。

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

此外,如果我注释掉include

,代码会正确编译并执行

3 个答案:

答案 0 :(得分:4)

如果你不在主函数中使用pthread_exit,那么所有创建的线程都将作为主要结束终止,即在你打印任何内容之前的情况下。

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

从pthread_exit手册页:

  

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

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

答案 1 :(得分:2)

pthread_exit只会终止主线程,但会让其他线程运行直到完成工作。 如果您从main返回或致电exit,则会强制查杀所有主题。

答案 2 :(得分:1)

你需要加入你的主题。没有pthread_exit的情况是你已经启动了线程,然后在实际运行任何线程之前主要退出。当主程序退出程序时,程序停止运行(与线程一样)。

通常你会使用pthread_join等待指定的线程完成执行。

似乎pthread_exit导致main等待我不知道的所有线程。然而,我会调查它,因为它不在文档中(据我所知),可能不是你想要依赖的东西。

编辑:在您的情况下,您根本不需要使用pthread_exit。当执行的函数(在您的情况下为printInfo)返回时,线程将自动终止。 pthread_exit允许您在执行的函数返回之前终止线程,例如,如果执行的函数调用另一个调用pthread_exit的函数。

相关问题