threads/thread_multijoin.c

This is threads/thread_multijoin.c (Listing 30-4, page 649), an example from the book, The Linux Programming Interface.

The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

This page shows the "distribution" or "book" version of the file (why are there two versions?), or the differences between the two versions. You can switch between the views using the tabs below.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.

  Cover of The Linux Programming Interface
+/* thread_multijoin.c
+
+   This program creates one thread for each of its command-line arguments.
+   Each thread sleeps for the number of seconds specified in the corresponding
+   command-line argument, and then terminates. This sleep interval simulates
+   "work" done by the thread.
+
+   The program maintains a global array (pointed to by 'thread') recording
+   information about all threads that have been created. The items of this
+   array record the thread ID ('tid') and current state ('state', of type
+   'enum tstate') of each thread.
+
+   As each thread terminates, it sets its 'state' to TS_TERMINATED and
+   signals the 'threadDied' condition variable. The main thread continuously
+   waits on this condition variable, and is thus informed when any of the
+   threads that it created has terminated. When 'numLive', which records
+   the number of live threads, falls to 0, the main thread terminates.
+*/
 #include <pthread.h>
 #include "tlpi_hdr.h"
 
 static int totThreads = 0;      /* Total number of threads created */
 static int numLive = 0;         /* Total number of threads still alive or
                                    terminated but not yet joined */
 static pthread_cond_t threadDied = PTHREAD_COND_INITIALIZER;
 static pthread_mutex_t threadMutex = PTHREAD_MUTEX_INITIALIZER;
                 /* Protects all of the following global variables */
 
 static int numUnjoined = 0;     /* Number of terminated threads that
                                    have not yet been joined */
 enum tstate {                   /* Thread states */
     TS_ALIVE,                   /* Thread is alive */
     TS_TERMINATED,              /* Thread terminated, not yet joined */
     TS_JOINED                   /* Thread terminated, and joined */
 };
 
 static struct {                 /* Info about each thread */
     pthread_t tid;              /* ID of this thread */
     enum tstate state;          /* Thread state (TS_* constants above) */
     int sleepTime;              /* Number seconds to live before terminating */
 } *thread;
 
 static void *                   /* Start function for thread */
 threadFunc(void *arg)
 {
     int idx = (int) arg;
     int s;
 
     sleep(thread[idx].sleepTime);       /* Simulate doing some work */
     printf("Thread %d terminating\n", idx);
 
     s = pthread_mutex_lock(&threadMutex);
     if (s != 0)
         errExitEN(s, "pthread_mutex_lock");
 
     numUnjoined++;
     thread[idx].state = TS_TERMINATED;
 
     s = pthread_mutex_unlock(&threadMutex);
     if (s != 0)
         errExitEN(s, "pthread_mutex_unlock");
     s = pthread_cond_signal(&threadDied);
     if (s != 0)
         errExitEN(s, "pthread_cond_signal");
 
     return NULL;
 }
 
 int
 main(int argc, char *argv[])
 {
     int s, idx;
 
     if (argc < 2 || strcmp(argv[1], "--help") == 0)
         usageErr("%s num-secs...\n", argv[0]);
 
     thread = calloc(argc - 1, sizeof(*thread));
     if (thread == NULL)
         errExit("calloc");
 
     /* Create all threads */
 
     for (idx = 0; idx < argc - 1; idx++) {
         thread[idx].sleepTime = getInt(argv[idx + 1], GN_NONNEG, NULL);
         thread[idx].state = TS_ALIVE;
         s = pthread_create(&thread[idx].tid, NULL, threadFunc, (void *) idx);
         if (s != 0)
             errExitEN(s, "pthread_create");
     }
 
     totThreads = argc - 1;
     numLive = totThreads;
 
     /* Join with terminated threads */
 
     while (numLive > 0) {
         s = pthread_mutex_lock(&threadMutex);
         if (s != 0)
             errExitEN(s, "pthread_mutex_lock");
 
         while (numUnjoined == 0) {
             s = pthread_cond_wait(&threadDied, &threadMutex);
             if (s != 0)
                 errExitEN(s, "pthread_cond_wait");
         }
 
         for (idx = 0; idx < totThreads; idx++) {
             if (thread[idx].state == TS_TERMINATED) {
                 s = pthread_join(thread[idx].tid, NULL);
                 if (s != 0)
                     errExitEN(s, "pthread_join");
 
                 thread[idx].state = TS_JOINED;
                 numLive--;
                 numUnjoined--;
 
                 printf("Reaped thread %d (numLive=%d)\n", idx, numLive);
             }
         }
 
         s = pthread_mutex_unlock(&threadMutex);
         if (s != 0)
             errExitEN(s, "pthread_mutex_unlock");
     }
 
     exit(EXIT_SUCCESS);
 }

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1