Monday, March 03, 2008

Joining Threads

If there are two threads, the following codes have problem:
main()
pthread_create(&thread_1, NULL, ..., ...);
pthread_create(&thread_2, NULL, ..., ...);
return 0;

How to make 'main' finish executing before the two threads are done?

One solution is pthread_join, which takes two arguments: the thread ID of the thread to wait for, and a pointer to a void* variable that will receive the finished thread’s return value.

main()
pthread_create(&thread_1, NULL, ..., ...);
pthread_create(&thread_2, NULL, ..., ...);
/* make sure 1st thread has finished. */
pthread_join (thread_1, NULL);
pthread_join (thread_2, NULL);
return 0;

No comments:

Post a Comment