Skip to main content
Engineering LibreTexts

9.3: Joining threads

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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)
        int ret = pthread_join(thread, NULL);
        if (ret == -1) {
          perror("pthread_join failed");

    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?

    This page titled 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) .

    • Was this article helpful?