I'm trying to create several thread workers in a function called engine_setup
, but every time the function returns, every thread stops as well. I tried to create pthread id as global pointer but didn't help.
here's the global:pthread_t * threadIDs;
the engine_setup function:
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;
}
and the thread function pointer is here:
void* tp(void * ptr){
query_helper * helper=(query_helper*)ptr;
while(1){
printf("1\n");
}
}
the output is something like this:
1
1
1
1
1
1
1
1
1
end setup
which shows that all the threads stopped when engine_setup return. Is there a way to keep them running?
Yes, you can call pthread_join(threadIds[i],null); (for all threads i), which will wait until the thred function returns.
You can use the second argument for storing return value from thread. I.e:
void *results[n_processors];
for(int i=0; i<n_processors; i++){
pthread_join(threadIds[i], &results[i]);
}