Concurrency basics with pthreads
15 min lesson
- Concurrency means running multiple tasks at the same time, and pthreads is the POSIX threads library that lets a C program create and manage threads.
- It matters because modern CPUs have many cores, and threads let a program use them for faster work or for handling multiple tasks at once.
- Think of threads as cooks in the same kitchen: they share the counters and tools, and they must coordinate so they do not bump into each other.
- A thread is an independent path of execution inside the same process, sharing memory with the other threads.
- pthread_create starts a new thread running a function, and pthread_join waits for a thread to finish.
- A mutex (pthread_mutex_t) is a lock that ensures only one thread at a time accesses shared data.
- The computer schedules threads on CPU cores and switches between them; without locks, two threads can read and write shared data at the same time and corrupt it, called a race condition.
- The syntax is: pthread_t t; pthread_create(&t, NULL, worker, arg); and pthread_mutex_lock(&m); ... pthread_mutex_unlock(&m);.
- A realistic use: summing a large array in parallel, or handling multiple client connections in a server.
- A surprising detail: adding a lock fixes correctness but can slow the program if the lock is held too long; keep critical sections short.
- The example program creates two threads that each add to a shared counter under a mutex, then joins them and prints the total.
- Share data between threads only under a mutex or other synchronization.
- Join every thread you create so the program waits for its work.
- Keep critical sections short to avoid slowing the program.
- Compile with -pthread on gcc, not just -lpthread.
- Concurrency is tricky but powerful. You are handling advanced material well!
#include <stdio.h>
#include <pthread.h>
// Shared data protected by a mutex
static int counter = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
// Each thread runs this function and adds to the counter
void *worker(void *arg) {
// Read how many increments this thread should do
int steps = *(int *)arg;
for (int i = 0; i < steps; i++) {
// Lock before touching shared data
pthread_mutex_lock(&lock);
counter++;
// Unlock as soon as we are done
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(void) {
// Two threads, each doing 1000 increments
pthread_t t1, t2;
int steps = 1000;
// Start both threads with the same worker function
pthread_create(&t1, NULL, worker, &steps);
pthread_create(&t2, NULL, worker, &steps);
// Wait for both to finish
pthread_join(t1, NULL);
pthread_join(t2, NULL);
// Print the total; it should be 2000
printf("Counter: %d\n", counter);
return 0;
}What happens: Counter: 2000
Breaking it down
Shared data and mutex
static int counter; static pthread_mutex_t lock;The counter is shared by all threads, and the mutex protects it. Initializing the mutex statically is simple and safe.
Worker function
void *worker(void *arg)The function each thread runs. The argument is passed as void * and cast back to the actual type.
Lock and unlock
pthread_mutex_lock(&lock); counter++; pthread_mutex_unlock(&lock);Only one thread at a time can increment the counter. This prevents lost updates from race conditions.
pthread_create
pthread_create(&t1, NULL, worker, &steps);Starts a new thread running worker with &steps as its argument.
pthread_join
pthread_join(t1, NULL);Waits for the thread to finish. Skipping join can end the program before the thread completes.
pthreads essentials
| Function | Purpose | Example |
|---|---|---|
| pthread_create | Start a thread | pthread_create(&t, NULL, f, arg) |
| pthread_join | Wait for a thread | pthread_join(t, NULL) |
| pthread_mutex_lock | Acquire a lock | pthread_mutex_lock(&m) |
| pthread_mutex_unlock | Release a lock | pthread_mutex_unlock(&m) |
| PTHREAD_MUTEX_INITIALIZER | Static init | static pthread_mutex_t m = ... |
A helpful analogy
Threads are like cooks in the same kitchen. They share counters and tools, so they must coordinate. A mutex is a single key to the oven: only the cook holding the key can use the oven, and everyone else waits. Without the key, two cooks might grab the same pan and ruin the dish.
Nesting rules
- 1.Every pthread_create must have a matching pthread_join unless the thread is detached.
- 2.Lock a mutex before accessing shared data and unlock it as soon as possible.
- 3.Pass data to threads via a pointer that stays valid for the thread's lifetime.
- 4.Compile with -pthread so both compiling and linking use thread support.
Common mistakes
Accessing shared data without a lock
Avoid
counter++; // from two threadsUse instead
pthread_mutex_lock(&lock); counter++; pthread_mutex_unlock(&lock);Concurrent reads and writes corrupt the value. The mutex serializes access so the increments are not lost.
Forgetting pthread_join
Avoid
pthread_create(&t, ...); // no joinUse instead
pthread_create(&t, ...); pthread_join(t, NULL);If main returns before the thread finishes, the process exits and the thread is killed. Join to wait for it.
Compiling without -pthread
Avoid
gcc main.c -o app // undefined referenceUse instead
gcc -pthread main.c -o appOn many systems the pthread library must be linked. -pthread also sets the right compile flags.
Quick tips
- •Run the example many times; the total should always be 2000 with the mutex.
- •Remove the mutex temporarily to see the race condition (results vary).
- •Keep shared state small and critical sections short.
- •Use tools like ThreadSanitizer (-fsanitize=thread) to catch races.
- •Read about atomics and condition variables as your next step.