Search⌘ K

Thread Completion

Explore how to wait for thread completion in concurrent programming by using the pthread_join function. Understand how to pass arguments and safely retrieve return values from threads, avoid common pitfalls like returning pointers to stack variables, and learn when joining threads is essential in multi-threaded applications.

We'll cover the following...

The example in the previous lesson shows how to create a thread. However, what happens if you want to wait for a thread to complete? You need to do something special in order to wait for completion; in particular, you must call the routine pthread_join().

pthread_join()

C
int pthread_join(pthread_t thread, void **value_ptr);

This routine takes two arguments. The first is of type pthread_t, and is used to specify which thread to wait for. This variable is initialized by the thread creation routine (when you pass a pointer to it as an argument to pthread_create()); if you keep it around, you can use it to wait for that thread to terminate.

The second argument is a pointer to the return value you expect to get back. Because the routine can return anything, it is defined to return a pointer to void; because the pthread_join() routine changes the value of ...