[英]multithreading process in C++, all threads are ended up without completion
我使用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;
}
在main中调用pthread_exit
之前,应先join
所有线程。
for (i = 0; i < NUM_THREADS; i++)
{
pthread_join(threads[i], 0);
}
你主要是做
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中,使其等待所有线程结束再继续
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.