A thread is one stream of instructions that runs inside your program alongside others. With several threads, a program can work on different parts of a job at the same time, using more than one CPU core. On Linux and macOS, C programs create threads with the POSIX threads library, known as pthreads. Threads are powerful, but they share memory, and that sharing is where the bugs live.
In this lesson you will learn
- What threads are and how they differ from processes
- How to create threads, pass them data and wait for them
- How to split a big calculation across several threads
- What a race condition is, and how a mutex prevents it
- How deadlocks happen and simple rules to avoid them
What Threads Give a Program
Think of a restaurant kitchen. One cook preparing every dish in turn is a single-threaded program. Four cooks working at once, sharing the same fridge and stove, are a multithreaded program: faster, but they must take turns with shared equipment.
| Process | Thread | |
|---|---|---|
| Memory | Each process has its own | All threads in a process share it |
| Cost to create | Higher | Lower |
| Communication | Needs pipes, sockets or shared memory set-up | Just read and write the same variables (carefully) |
| If one crashes | Others keep running | The whole process usually dies |
Threads help in two main situations: speed, by splitting heavy work across CPU cores, and responsiveness, by letting one thread wait for a network or a disk while others keep working.
Creating, Joining and Passing Data to Threads
Three calls from <pthread.h> do most of the work:
pthread_create(&id, NULL, function, arg)starts a new thread runningfunction(arg).- The thread function must have the form
void *function(void *arg). Pass several values by putting them in a struct and passing its address. pthread_join(id, NULL)waits until that thread has finished.
A Parallel Sum With pthreads
This program adds the numbers from 1 to 1,000,000 by giving each of four threads a quarter of the range.
#include <stdio.h>
#include <pthread.h>
typedef struct { int id; int from, to; long sum; } Job;
static void *add_range(void *arg) {
Job *job = arg;
for (int i = job->from; i <= job->to; i++) job->sum += i;
return NULL;
}
int main(void) {
Job jobs[4];
pthread_t threads[4];
for (int t = 0; t < 4; t++) { /* split 1..1000000 into 4 parts */
jobs[t] = (Job){ t, t * 250000 + 1, (t + 1) * 250000, 0 };
pthread_create(&threads[t], NULL, add_range, &jobs[t]);
}
long total = 0;
for (int t = 0; t < 4; t++) {
pthread_join(threads[t], NULL); /* wait for each thread */
printf("thread %d summed %d..%d = %ld\n", jobs[t].id, jobs[t].from, jobs[t].to, jobs[t].sum);
total += jobs[t].sum;
}
printf("total = %ld\n", total);
return 0;
}
gcc -std=c11 -Wall -Wextra -pthread sum.c -o sum
./sum
Output
thread 0 summed 1..250000 = 31250125000
thread 1 summed 250001..500000 = 93750125000
thread 2 summed 500001..750000 = 156250125000
thread 3 summed 750001..1000000 = 218750125000
total = 500000500000
Each thread writes only to its own Job struct, so the threads never touch the same data. That is the simplest and safest design: give each thread its own piece of work and its own place for the result, then combine the results after joining.
The threads may finish in any order. The program prints in a fixed order only because it joins them in order 0, 1, 2, 3. Always compile with -pthread, which sets up both the compiler and the linker for threads.
Race Conditions and Deadlocks
Race Conditions
Problems start when two threads change the same variable. count++ looks like one step, but the CPU does three: read the value, add one, write it back. If two threads read the same old value at the same moment, both write back the same new value and one increment is lost. This is a race condition.
Without protection, four threads each adding 100,000 to a shared counter will often end with a total below 400,000, and a different total on every run. That unpredictability is what makes races so hard to debug.
The fix is a mutex (mutual exclusion lock). Only one thread can hold it at a time; others wait their turn.
#include <stdio.h>
#include <pthread.h>
static long tickets_sold = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void *sell(void *arg) {
(void)arg;
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&lock); /* only one thread at a time in here */
tickets_sold++;
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(void) {
pthread_t counters[4];
for (int t = 0; t < 4; t++) pthread_create(&counters[t], NULL, sell, NULL);
for (int t = 0; t < 4; t++) pthread_join(counters[t], NULL);
printf("tickets sold: %ld (expected 400000)\n", tickets_sold);
return 0;
}
Output
tickets sold: 400000 (expected 400000)
The code between pthread_mutex_lock and pthread_mutex_unlock is called a critical section. Keep critical sections short, because while one thread holds the lock, the others are blocked. Here, a faster design would let each thread count privately and add its total to the shared counter once at the end.
Deadlocks
A deadlock happens when threads wait for each other forever. Thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Neither can continue. Three simple rules prevent most deadlocks:
- If a thread needs several locks, every thread must take them in the same order.
- Never return from a function, or exit a loop early, while still holding a lock.
- Avoid calling unknown code (such as a callback) while holding a lock.
Thread Safety Checklist
- Prefer giving each thread its own data; share as little as possible.
- Protect every shared variable that any thread writes, using a mutex.
- Check the return value of
pthread_create; it returns 0 on success. - Join every thread you create (or detach it), so its resources are released.
- Do not pass the address of a loop variable to several threads; it changes as the loop runs. Give each thread its own struct, as in the parallel sum.
- Test with
-fsanitize=thread(ThreadSanitizer), which reports data races. - Remember that some library functions, like
strtokandrand, are not thread-safe.
Practice Exercises
Exercise 1. Why does pthread_create(&t[i], NULL, work, &i); inside a for loop often give threads the wrong number?
Show answer
All threads receive the address of the same variable i, which keeps changing. By the time a thread reads it, the loop may have moved on. Give each thread its own copy, for example in an array int ids[N].
Exercise 2. Change the ticket program so each thread counts in a local variable and adds to tickets_sold only once. How many times is the mutex locked now?
Show answer
Four times in total (once per thread) instead of 400,000, which is much faster. The result is still exactly 400,000.
Exercise 3. What happens if main returns without calling pthread_join?
Show answer
Returning from main ends the whole process, so unfinished threads are stopped part-way and their results are lost.
Frequently Asked Questions
Do pthreads work on Windows?
Not natively. Windows has its own thread API, though MinGW-w64 provides a pthreads layer. C11 also defines portable threads in <threads.h>, but support varies between compilers.
Will more threads always make my program faster?
No. Beyond the number of CPU cores, extra threads just take turns. Locks and shared data can also make a threaded program slower than a single-threaded one.
Is volatile enough to make a variable thread-safe?
No. volatile does not make operations atomic or ordered. Use a mutex or C11 atomics from <stdatomic.h>.
Summary
- Threads run parts of one program at the same time and share its memory.
- Use
pthread_createto start a thread andpthread_jointo wait for it; compile with-pthread. - Give each thread its own data where possible.
- Protect shared variables with a mutex to prevent race conditions.
- Take multiple locks in the same order everywhere to avoid deadlocks.
