Rejoining threads in C
In my main function, I spawn j threads which 开发者_运维技巧all compute the same task in parallel -- and then I want to wait for them to finish before exiting.
int main(...) {
// ...
int threads = 6;
pthread_t* thread = malloc(sizeof(pthread_t)*threads);
for(i = 0; i < threads; i++) {
struct thread_param *tp;
tp = malloc(sizeof(*tp));
// ...
int ret = pthread_create(&thread[i], NULL, &control, (void*)tp);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}
for (j = 0; j < threads; j++) {
printf("JOINING THREAD: %i\n", j);
pthread_join( &thread[j], NULL);
}
exit(0);
}
However, nothing waits. Main just exits without ever completing the threaded tasks. Am I missing something?
hey, try pthread_join( thread[j], NULL);
i think the problem is with types. I checked docs:
int pthread_join(pthread_t thread, void **value_ptr);
and thread
is p_thread*
, and thread[j]
is p_thread
, while &thread[j]
is p_thread*
, which is invalid. There just might internal error happen.
Edit: Yeah, I am very positive with that, pthread_t
is basically int
, so pthread_t*
is accepted, it is just invalid thread handle, so pthread_join
fails internally.
精彩评论