Skip to content

Pthread Common Patterns

Lately, I’ve been working with pthreads, and I wanted to write about its basic APIs. I think the syntax itself is less important, since there are other tools like OpenMP. Instead, the goal is to understand patterns that carry over across libraries and to practice thinking about multithreaded programs.

I wrote five simple programs to illustrate the usage of pthread_create/pthread_join, pthread_detach, pthread_mutex_*, pthread_cond_*, and pthread_barrier_*. Let’s look at each one.


Let’s look at the first example. This program creates four threads inside main, and each thread executes run. Inside run, each thread generates a random value and saves it in its dynamically allocated arg_t struct. Once all threads have finished, main adds up their values and prints the total.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef struct thread_arg {
int tid;
int val;
} arg_t;
void *run(void *arg)
{
arg_t *a = (arg_t *) arg;
// rand() isn't guaranteed to be thread-safe,
// but it is on Linux with glibc.
int x = rand() % 10 + 1;
sleep(x);
a->val = x;
printf("Hello from thread %d: My value is %d.\n", a->tid, a->val);
return NULL;
}
int main()
{
int num_threads = 4;
pthread_t *threads = calloc(num_threads, sizeof(pthread_t));
arg_t *args = calloc(num_threads, sizeof(arg_t));
if (!threads || !args) {
fprintf(stderr, "Malloc failed.\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < num_threads; ++i) {
args[i].tid = i;
int error = pthread_create(
&threads[i], // pthread_create writes the thread identifier here
NULL, // can pass in pthread_attr_t for advanced use
run, // thread routine
&args[i] // arg to the routine
);
// pthread_create returns 0 if successful.
if (error) {
fprintf(stderr, "pthread_create: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < num_threads; ++i) {
// pthread_join is blocking, so even if thread 1 finishes before thread 0,
// we first wait for pthread_join(threads[0]) to return.
int error = pthread_join(threads[i], NULL);
if (error) {
fprintf(stderr, "pthread_join: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
}
int total = 0;
for (int i = 0; i < num_threads; ++i) {
total += args[i].val;
}
printf("Total is: %d\n", total);
free(threads);
free(args);
return 0;
}

Let’s first look at pthread_create. The high-level pattern is to create a thread that executes a given routine.

Note how we allocate memory for the pthread_t array and the thread arguments. pthread_create writes the new thread’s identifier into the pthread_t we provide. We don’t need to know how this identifier is represented internally, but as we see later, we pass each pthread_t to pthread_join.

While we dynamically allocated memory for both the pthread_t and arg_t, we could have used stack arrays instead. Passing their addresses to run still allows it to access them, as long as they remain valid until the threads finish.

pthread_t threads[4];
arg_t args[4];

Also note that run should accept a void *, which we cast to arg_t * at the beginning.

After we create the threads, the main thread continues executing. If it returns from main before the workers finish their work, the process exits without waiting for them. pthread_join is one way to wait for the threads to finish. In this example, we join thread 0, thread 1, and so on in a loop.

pthread_join is blocking, so we first wait for thread 0 to finish even if other threads have already finished. Once we have joined all threads, we compute the sum and return.


Example 2 is very similar to example 1, but we use pthread_detach instead of pthread_join.

In the previous example, the main thread waited for all worker threads to finish and then computed the sum. This pattern is useful when we need to perform some action after a thread finishes.

But in some cases, threads don’t need to report back and can finish on their own. In this example, each thread generates and prints a random value. We don’t compute the sum at the end.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef struct thread_arg {
int tid;
} arg_t;
void *run(void *arg)
{
arg_t *a = (arg_t *) arg;
// rand() isn't guaranteed to be thread-safe,
// but it is on Linux with glibc.
int x = rand() % 10 + 1;
sleep(x);
printf("Hello from thread %d: My value is %d.\n", a->tid, x);
free(a);
return NULL;
}
int main()
{
int num_threads = 4;
for (int i = 0; i < num_threads; ++i) {
pthread_t thread;
arg_t *arg = calloc(1, sizeof(arg_t));
if (!arg) {
fprintf(stderr, "Malloc failed.\n");
exit(EXIT_FAILURE);
}
arg->tid = i;
int error = pthread_create(
&thread,
NULL,
run,
arg
);
if (error) {
fprintf(stderr, "pthread_create: %s\n", strerror(error));
free(arg);
exit(EXIT_FAILURE);
}
// pthread_detach returns 0 if successful.
error = pthread_detach(thread);
if (error) {
fprintf(stderr, "pthread_detach: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
}
// Returning from main would terminate the entire process,
// including any workers that are still running.
// pthread_exit terminates only the main thread.
// The process exits when the last thread finishes.
pthread_exit(NULL);
}

There are several things to note here. First, after creating each thread, we detach it right away inside the for loop. We also free each thread’s argument memory inside run now. We can’t safely free it in main without knowing whether the thread is still using it.

Instead of return 0, we now have pthread_exit(NULL). This terminates only the main thread, allowing the worker threads to continue running. The process exits when the last thread finishes.


The third example demonstrates the use of mutexes to safely update state shared between threads. After we initialize a mutex, we can use pthread_mutex_lock and pthread_mutex_unlock to protect a critical section. Only one thread can hold the lock and execute that section at a time. Here, the threads update the shared total value.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int total = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct thread_arg {
int tid;
} arg_t;
void *run(void *arg)
{
arg_t *a = (arg_t *) arg;
// rand() isn't guaranteed to be thread-safe,
// but it is on Linux with glibc.
int x = rand() % 10 + 1;
sleep(x);
pthread_mutex_lock(&mutex);
total += x;
printf("Hello from thread %d: Adding %d to total. Total is now %d.\n",
a->tid, x, total);
pthread_mutex_unlock(&mutex);
free(a);
return NULL;
}
int main()
{
int num_threads = 4;
for (int i = 0; i < num_threads; ++i) {
pthread_t thread;
arg_t *arg = calloc(1, sizeof(arg_t));
if (!arg) {
fprintf(stderr, "Malloc failed.\n");
exit(EXIT_FAILURE);
}
arg->tid = i;
int error = pthread_create(
&thread,
NULL,
run,
arg
);
if (error) {
fprintf(stderr, "pthread_create: %s\n", strerror(error));
free(arg);
exit(EXIT_FAILURE);
}
error = pthread_detach(thread);
if (error) {
fprintf(stderr, "pthread_detach: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
}
pthread_exit(NULL);
}

I think the example is straightforward, so I won’t go into detail. The common pattern is to acquire and release the lock inside the thread’s routine. It’s best to keep the critical section small by acquiring the lock just before accessing shared state. In our example, we generate the random value outside the critical section.


Let’s say we have a producer and a consumer, and a queue of size 1. The producer produces a new value only if the queue is empty. The consumer reads and consumes the value only if the producer has written a new value to the queue.

One way to implement this is to have the producer and consumer repeatedly poll the queue to check its state, but this wastes CPU cycles. Pthread condition variables offer a way for threads to sleep while waiting for a condition to change.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int value;
int has_value;
int N = 5;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
typedef struct thread_arg {
// Number of items currently processed.
int curr;
} arg_t;
void *producer_run(void *arg)
{
arg_t *a = (arg_t *) arg;
while (a->curr < N) {
pthread_mutex_lock(&mutex);
while (has_value != 0) {
// The thread atomically releases the mutex and blocks,
// waiting for a notification on the condition variable.
// When it wakes up, it reacquires the mutex before
// pthread_cond_wait returns.
pthread_cond_wait(&cond, &mutex);
}
// rand() isn't guaranteed to be thread-safe,
// but it is on Linux with glibc.
int x = rand() % 10 + 1;
value = x;
has_value = 1;
printf("Hello from producer: Produced %d.\n", x);
// pthread_cond_signal wakes up one thread waiting on this condition variable.
// With one producer and one consumer, only the other thread can be waiting.
// Another option is to use pthread_cond_broadcast, which
// wakes up all threads waiting on this condition variable.
// A thread that wakes up still needs to be scheduled and reacquire
// the mutex before pthread_cond_wait returns.
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
a->curr++;
}
return NULL;
}
void *consumer_run(void *arg)
{
arg_t *a = (arg_t *) arg;
while (a->curr < N) {
pthread_mutex_lock(&mutex);
while (has_value == 0) {
pthread_cond_wait(&cond, &mutex);
}
printf("Hello from consumer: Consumed %d.\n", value);
value = 0;
has_value = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
a->curr++;
}
return NULL;
}
int main()
{
arg_t *arg = calloc(2, sizeof(arg_t));
if (!arg) {
fprintf(stderr, "Malloc failed.\n");
exit(EXIT_FAILURE);
}
pthread_t producer;
int error = pthread_create(&producer, NULL, producer_run, &arg[0]);
if (error) {
fprintf(stderr, "pthread_create: %s\n", strerror(error));
free(arg);
exit(EXIT_FAILURE);
}
pthread_t consumer;
error = pthread_create(&consumer, NULL, consumer_run, &arg[1]);
if (error) {
fprintf(stderr, "pthread_create: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
error = pthread_join(producer, NULL);
if (error) {
fprintf(stderr, "pthread_join: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
error = pthread_join(consumer, NULL);
if (error) {
fprintf(stderr, "pthread_join: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
free(arg);
return 0;
}

The condition variable is a pthread object that facilitates coordination rather than the boolean value we actually check. The actual condition is represented by the has_value flag here.

Both the producer and the consumer follow a similar pattern. First, each takes the lock and checks the condition. If the condition is not satisfied, it calls pthread_cond_wait, which releases the lock and puts the thread to sleep.

When the thread wakes up, it reacquires the lock before pthread_cond_wait returns, then checks the condition again. This check happens in a while loop because a thread can wake up even without a signal, and waking up doesn’t guarantee that the condition has been met. Once the condition is satisfied, the producer or consumer performs its action, then signals the other thread before releasing the lock.

Signaling a waiting thread wakes it up, but that doesn’t mean it runs immediately. It still needs to be scheduled and reacquire the lock. pthread_cond_signal wakes up one thread waiting on the condition variable, without guaranteeing which one. This is fine here because we only have one producer and one consumer. We can also use pthread_cond_broadcast to signal all threads waiting on the condition variable.


Last but not least, let’s take a look at barriers.

Barriers provide a way for threads to coordinate between stages of work. For example, in a two-phase workload, all threads might need to finish phase 1 before any thread can move on to phase 2. We can achieve this by placing a barrier between the phases, where each thread waits until all participating threads have arrived.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
pthread_barrier_t barrier;
typedef struct thread_arg {
int tid;
} arg_t;
void *run(void *arg)
{
arg_t *a = (arg_t *) arg;
int x = rand() % 10 + 1;
sleep(x);
printf("Thread %d: Ready\n", a->tid);
pthread_barrier_wait(&barrier);
printf("Thread %d: Starting next phase\n", a->tid);
return NULL;
}
int main()
{
int num_threads = 4;
int error = pthread_barrier_init(&barrier, NULL, num_threads);
if (error) {
fprintf(stderr, "pthread_barrier_init: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
pthread_t *threads = calloc(num_threads, sizeof(pthread_t));
arg_t *args = calloc(num_threads, sizeof(arg_t));
if (!threads || !args) {
fprintf(stderr, "Malloc failed.\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < num_threads; ++i) {
args[i].tid = i;
error = pthread_create(
&threads[i],
NULL,
run,
&args[i]
);
if (error) {
fprintf(stderr, "pthread_create: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < num_threads; ++i) {
error = pthread_join(threads[i], NULL);
if (error) {
fprintf(stderr, "pthread_join: %s\n", strerror(error));
exit(EXIT_FAILURE);
}
}
pthread_barrier_destroy(&barrier);
free(threads);
free(args);
return 0;
}

Again, the program is relatively straightforward, so I won’t go into detail. After initializing the barrier inside main, each thread can call pthread_barrier_wait inside run to wait until all participating threads have reached that point.


Hopefully, these examples are a good starting point for reviewing multithreading. Sometimes, it’s hard to wrap my head around these concepts and feel confident that I actually understand what’s happening under the hood, but I hope I’ll get there one day.