0

我使用 pthread.h 运行以下代码...运行时,在线程完成之前,代码退出...

我附上代码...

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

using namespace std;

#define NUM_THREADS 5

void *PrintHello(void *threadid)
{
    long tid = (long)threadid;
    cout<<"Hello World! Thread ID,"<<tid<<endl;
    pthread_exit(NULL);
    return &tid;
}

int main()
{
    pthread_t threads[NUM_THREADS];
    int rc;
    int i;

    for(i=0;i<NUM_THREADS;i++)
    {
        cout<<"main() : creating thread,"<<i<<endl;
        rc = pthread_create(&threads[i],NULL,PrintHello,(void*)i);
        //sleep(1);
        if(rc)
        {
            cout<<"Error:Unable to create thread,"<<rc<<endl;
            exit(-1);
        }
    }

    pthread_exit(NULL);

    return 0;
}
4

2 回答 2

3

您应该join在调用pthread_exitmain 之前的所有线程。

for (i = 0; i < NUM_THREADS; i++)
{
   pthread_join(threads[i], 0);
}
于 2013-04-18T08:53:02.533 回答
1

在你的主要工作中,

   pthread_exit(NULL); // this causes main to do its own work and exit. 
                       // and the other thread will keep running at its own pace

如此处所述

你必须使用类似的东西

for (i = 0; i < NUM_THREADS; i++)
{
   pthread_join(&threads[i],NULL);
}

在 main 中使其等待所有线程结束,然后再继续

于 2013-04-18T08:56:57.297 回答