
When one thread wants to wait for another thread to complete, it invokes pthread_join. Here is my wrapper for pthread_join:

void join_thread(pthread_t thread)
{
if (ret == -1) {
exit(-1);
}
}


The parameter is the handle of the thread you want to wait for. All the wrapper does is call pthread_join and check the result.

Any thread can join any other thread, but in the most common pattern the parent thread creates and joins all child threads. Continuing the example from the previous section, here’s the code that waits on the children:

    for (i=0; i<NUM_CHILDREN; i++) {
}


This loops waits for the children one at a time in the order they were created. There is no guarantee that the child threads complete in that order, but this loop works correctly even if they don’t. If one of the children is late, the loop might have to wait, and other children might complete in the meantime. But regardless, the loop exits only when all children are done.

If you have downloaded the repository for this book (see Section 0.2), you’ll find this example in counter/counter.c. You can compile and run it like this:

$make counter gcc -Wall counter.c -o counter -lpthread$ ./counter


When I ran it with 5 children, I got the following output:

counter = 0
counter = 0
counter = 1
counter = 0
counter = 3


When you run it, you will probably get different results. And if you run it again, you might get different results each time. What’s going on?

9.3: Joining threads is shared under a CC BY-NC license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .