线程在函数 return 后停止
Threads stopped after function return
我试图在一个名为 engine_setup
的函数中创建多个线程工作者,但每次函数 return 时,每个线程也会停止。我试图将 pthread id 创建为全局指针但没有帮助。
这是全球:pthread_t * threadIDs;
engine_setup 函数:
query_helper* engine_setup(size_t n_processors) {
//some code that is not relevant
int err;
threadIDs=malloc(n_processors*sizeof(*threadIDs));
for(int i=0;i<n_processors;i++){
err = pthread_create(&threadIDs[i],NULL,tp,(void*)helper);
if (err != 0)
printf("can't create thread \n");
}
printf("end setup\n");
return helper;
}
线程函数指针在这里:
void* tp(void * ptr){
query_helper * helper=(query_helper*)ptr;
while(1){
printf("1\n");
}
}
输出是这样的:
1
1
1
1
1
1
1
1
1
end setup
这表明所有线程在 engine_setup return 时停止。有什么办法可以保留它们 运行?
你的程序在函数returns后退出了吗?如果是这样,您希望在每个线程上使用 pthread_join,以便程序在退出之前等待每个线程终止。
是的,你可以调用pthread_join(threadIds[i],null); (对于所有线程 i),它将等到 thred 函数 returns.
您可以使用第二个参数来存储来自线程的 return 值。
即:
void *results[n_processors];
for(int i=0; i<n_processors; i++){
pthread_join(threadIds[i], &results[i]);
}
我试图在一个名为 engine_setup
的函数中创建多个线程工作者,但每次函数 return 时,每个线程也会停止。我试图将 pthread id 创建为全局指针但没有帮助。
这是全球:pthread_t * threadIDs;
engine_setup 函数:
query_helper* engine_setup(size_t n_processors) {
//some code that is not relevant
int err;
threadIDs=malloc(n_processors*sizeof(*threadIDs));
for(int i=0;i<n_processors;i++){
err = pthread_create(&threadIDs[i],NULL,tp,(void*)helper);
if (err != 0)
printf("can't create thread \n");
}
printf("end setup\n");
return helper;
}
线程函数指针在这里:
void* tp(void * ptr){
query_helper * helper=(query_helper*)ptr;
while(1){
printf("1\n");
}
}
输出是这样的:
1
1
1
1
1
1
1
1
1
end setup
这表明所有线程在 engine_setup return 时停止。有什么办法可以保留它们 运行?
你的程序在函数returns后退出了吗?如果是这样,您希望在每个线程上使用 pthread_join,以便程序在退出之前等待每个线程终止。
是的,你可以调用pthread_join(threadIds[i],null); (对于所有线程 i),它将等到 thred 函数 returns.
您可以使用第二个参数来存储来自线程的 return 值。 即:
void *results[n_processors];
for(int i=0; i<n_processors; i++){
pthread_join(threadIds[i], &results[i]);
}