The Complete Guide to Threads in C, C++ and Rust
Learn threads from first principles in C with pthreads, C++ with std::thread and jthread, and Rust: create, join, share data, stop, name and debug them.

A single-threaded program does one thing at a time. That is the right model until the program has to wait for a disk while computing, serve two clients at once, or use more than one of the cores on the machine it runs on. A thread is the operating system's answer: a second flow of control inside the same process, running the same code, looking at the same memory. It is also the origin of the hardest bugs in systems programming, because the sharing that makes threads cheap is the same sharing that lets two of them corrupt a variable at the same instant. This guide is the map for the whole Threads cluster. It teaches what a thread is, how to create, join, name, stop and debug one in C with POSIX threads, in C++ with std::thread and std::jthread, and in Rust with std::thread, and it shows where each language protects you and where it leaves you alone. The worked examples use Linux with glibc 2.41, GCC 15, Clang 20 and Rust 1.90.
If you want only one idea out of it, it is this: a thread is cheap to start and expensive to get wrong, so give every thread its own data and a clear end of life, and share only what you must, behind a rule you can state in one sentence.
What a thread is, in one page
A process owns resources: an address space, open files, signal handlers, credentials. A thread owns only what it needs to run: a stack, a set of registers, a signal mask, an errno and some thread-local storage. All the threads of a process see the same memory, so one thread can write a value and another can read it with no copying and no system call. On Linux each thread is a kernel task created with clone3 and the sharing flags CLONE_VM, CLONE_FILES, CLONE_SIGHAND and CLONE_THREAD, and the scheduler treats it like any other runnable task. The kernel mechanics are in how Linux implements threads, and the difference from a process is spelled out in processes vs threads.
Three consequences organize everything else in this guide:
Lifetime. A thread has a start and an end, and something has to decide when it ends and who cleans up. Joining, detaching and stopping are the three answers.
Sharing. Everything reachable by two threads is shared. Locals on a stack are private by accident, globals and the heap are shared by default, and the rules for sharing safely are the subject of the neighboring clusters on locks, atomics and memory ordering.
Failure. A crash in one thread takes down the whole process, and an exception or panic in a thread does not reach the code that started it unless you carry it there.
Your first thread in three languages
The smallest correct program does three things: start a thread, let it do work, wait for it to finish. Here it is in C:
#include <pthread.h>
#include <stdio.h>
static void *greet(void *arg)
{
printf("hello from %s\n", (const char *)arg);
return NULL;
}
int main(void)
{
pthread_t worker;
if (pthread_create(&worker, NULL, greet, "the worker") != 0)
return 1;
pthread_join(worker, NULL);
printf("worker finished\n");
return 0;
}In C++20:
#include <iostream>
#include <thread>
int main()
{
std::jthread worker([] { std::cout << "hello from the worker\n"; });
worker.join();
std::cout << "worker finished\n";
}In Rust:
use std::thread;
fn main() {
let worker = thread::spawn(|| {
println!("hello from the worker");
});
worker.join().unwrap();
println!("worker finished");
}Each program prints the greeting first and "worker finished" second, because the join returns only after the thread has ended:
hello from the worker
worker finishedThe C version prints "hello from the worker" with the string passed as the argument. Build the C program with gcc -Wall -Wextra -pthread -o first first.c, the C++ one with g++ -std=c++20 -Wall -Wextra -pthread -o first first.cpp, and the Rust one with cargo run. Note -pthread on both compile and link lines; glibc 2.34 and later hide a missing flag, and older systems do not, as the linking post explains.
The details of each API are in pthread_create and pthread_join, std::thread and std::jthread and std::thread::spawn. The next sections extract the rules that hold in all three.
The error convention in each language
Creation can fail. A process has a limit on threads, a container may cap them, and memory for the stack may run out. Each language reports that differently, and handling it is part of correct code:
| Language | How create reports failure | Idiom |
|---|---|---|
| C | Returns an error number (not -1, not errno) | int rc = pthread_create(...); if (rc) ... |
| C++ | Throws std::system_error | try { std::jthread t(f); } catch (const std::system_error &e) {} |
| Rust | thread::spawn panics; thread::Builder::spawn returns io::Result | Use the builder where failure must be handled |
A C program that ignores the return value of pthread_create and then joins an uninitialized handle has undefined behavior, which is the most common pthreads bug in beginner code. A short macro keeps the checks honest:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CHECK_PTHREAD(call) \
do { \
int rc_ = (call); \
if (rc_ != 0) { \
fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, \
#call, strerror(rc_)); \
exit(EXIT_FAILURE); \
} \
} while (0)The same logic in Rust, with the builder:
use std::thread;
fn main() -> std::io::Result<()> {
let handle = thread::Builder::new()
.name("checked".to_string())
.spawn(|| println!("started"))?;
handle.join().unwrap();
Ok(())
}startedThe ? returns the creation error to the caller instead of panicking. In a server that spawns threads on behalf of users this is the difference between rejecting a request and crashing.
Passing data in and getting results out
A thread starts with one argument and, when it ends, produces at most one result. The languages differ in how much they check.
In C, both are void *, so the compiler checks nothing. The dependable pattern is a struct that holds inputs and outputs, owned by the creator:
#include <pthread.h>
#include <stdio.h>
struct job {
int first, last; /* inputs */
long sum; /* output */
};
static void *sum_range(void *arg)
{
struct job *job = arg;
long total = 0;
for (int i = job->first; i <= job->last; i++)
total += i;
job->sum = total;
return NULL;
}
int main(void)
{
struct job jobs[2] = { { 1, 50, 0 }, { 51, 100, 0 } };
pthread_t t[2];
for (int i = 0; i < 2; i++)
pthread_create(&t[i], NULL, sum_range, &jobs[i]);
for (int i = 0; i < 2; i++)
pthread_join(t[i], NULL);
printf("sum 1..100 = %ld\n", jobs[0].sum + jobs[1].sum);
return 0;
}sum 1..100 = 5050The two threads write to different structs, so nothing is shared mutably, and the joins make the writes visible to main. The common mistakes, passing the address of a loop counter and returning a pointer to a local, are catalogued in passing arguments to pthreads.
In C++, the constructor copies the arguments into the thread, and a result goes back through a std::future, a captured reference or a slot you own:
#include <future>
#include <iostream>
#include <thread>
long sum_range(int first, int last)
{
long total = 0;
for (int i = first; i <= last; ++i)
total += i;
return total;
}
int main()
{
std::promise<long> low_half;
std::future<long> low = low_half.get_future();
std::jthread worker([p = std::move(low_half)]() mutable {
p.set_value(sum_range(1, 50));
});
long high = sum_range(51, 100);
std::cout << "sum 1..100 = " << low.get() + high << '\n';
}sum 1..100 = 5050The calling thread computes the upper half itself while the worker does the lower half, then get() blocks until the promise is fulfilled. In Rust, the closure's return value comes back through join():
use std::thread;
fn sum_range(first: u64, last: u64) -> u64 {
(first..=last).sum()
}
fn main() {
let worker = thread::spawn(|| sum_range(1, 50));
let high = sum_range(51, 100);
let low = worker.join().unwrap();
println!("sum 1..100 = {}", low + high);
}sum 1..100 = 5050Rust adds a rule the others lack: the closure given to spawn must be 'static and Send. Borrowing a local fails to compile with E0373. That is the compiler refusing a dangling pointer, and the fix is either move or scoped threads, described next.
Borrowing stack data safely
C and C++ let you pass a pointer to a local variable to a thread, and it is safe if and only if you join the thread before the local goes out of scope. Nothing checks that you did. Rust's scoped threads encode it in the type system:
use std::thread;
fn main() {
let mut data = vec![1, 2, 3, 4, 5, 6];
thread::scope(|s| {
for chunk in data.chunks_mut(3) {
s.spawn(move || {
for value in chunk.iter_mut() {
*value *= 10;
}
});
}
});
println!("{:?}", data);
}[10, 20, 30, 40, 50, 60]thread::scope joins every thread it started before it returns, so the threads can borrow data, and chunks_mut gives each thread an exclusive, non-overlapping slice. The compiler proves there is no aliasing. Borrowing stack data with thread::scope covers the rules. In C and C++ the equivalent discipline is manual: join before the locals die, give each thread a disjoint range, and review the code for the join.
Joining, detaching and ending a thread
Every thread must end in one of three ways:
| Ending | C | C++ | Rust |
|---|---|---|---|
| Join: wait for it and collect the result | pthread_join | join() | JoinHandle::join |
| Detach: let it clean up and run on its own | pthread_detach | detach() | Drop the handle |
| Stop: ask it to finish early | A flag, or pthread_cancel | std::stop_token | A flag or channel |
A joinable thread that is never joined leaks its resources in C and calls std::terminate in C++ if the std::thread object is destroyed first. Rust never aborts for a dropped handle but may kill the thread at process exit. C++20's std::jthread removes the trap by joining in its destructor.
Detaching trades control for convenience. A detached thread frees itself, but it cannot be joined, returns nothing and is killed when the process exits, so it must own the data it uses. Detaching and leak avoidance covers the pattern in C:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
static sem_t done;
static void *background(void *arg)
{
(void)arg;
puts("background work");
sem_post(&done);
return NULL;
}
int main(void)
{
sem_init(&done, 0, 0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t t;
pthread_create(&t, &attr, background, NULL);
pthread_attr_destroy(&attr);
sem_wait(&done);
puts("main saw it finish");
return 0;
}background work
main saw it finishThe semaphore stands in for the join that a detached thread cannot have.
Stopping a thread early
There is no safe way to kill a thread from outside. Every language that tries makes you pay. The honest option is cooperative: the thread checks a flag and returns. In C, an atomic flag does it:
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <unistd.h>
static atomic_bool stop_requested;
static void *worker(void *arg)
{
(void)arg;
while (!atomic_load(&stop_requested))
usleep(1000);
puts("worker: stop seen, cleaning up");
return NULL;
}
int main(void)
{
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
usleep(20 * 1000);
atomic_store(&stop_requested, 1);
pthread_join(t, NULL);
puts("main: worker joined");
return 0;
}worker: stop seen, cleaning up
main: worker joinedC++20 packages the flag as std::stop_token, and Rust threads usually use an AtomicBool or a channel; the C++ API is in stopping C++ threads. The forceful alternative in C, pthread_cancel, requires cleanup handlers for every lock and allocation the thread holds, and it breaks C++ destructors unless the stack unwinds correctly. Cancelling threads safely explains when it is justified. Rust has no cancel call at all.
Failure inside a thread
A thread that fails must not fail silently, and must not take the process down by accident. The behavior differs:
| Failure | C | C++ | Rust |
|---|---|---|---|
| Runtime error | Return code | Exception | Panic |
| Reaches the creator | Only if returned | No: std::terminate unless captured | Yes: join() returns Err |
| Default result | Silent if ignored | Process aborts | Process continues |
In C++, an exception that escapes the thread function kills the process. Capture it with std::exception_ptr, as propagating worker exceptions shows. In Rust, a panic unwinds only that thread, and join() hands you the failure:
use std::thread;
fn main() {
let result = thread::spawn(|| {
let values: Vec<i32> = Vec::new();
values[0]
})
.join();
match result {
Ok(v) => println!("value {v}"),
Err(_) => println!("the worker panicked, the program continues"),
}
}thread '<unnamed>' panicked at src/main.rs:5:9:
index out of bounds: the len is 0 but the index is 0
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
the worker panicked, the program continuesNote the exception to the Rust behavior: if the Cargo profile sets panic = "abort", any panic ends the process.
Thread-local data
Sometimes the right answer to "how do I share this safely" is "do not share it". Thread-local storage gives each thread its own copy, so no synchronization is needed. The keywords are _Thread_local in C, thread_local in C++ and the thread_local! macro in Rust, all compared in thread-local storage in C, C++ and Rust. The C form:
#include <pthread.h>
#include <stdio.h>
static _Thread_local int requests_handled;
static void *worker(void *arg)
{
int n = *(int *)arg;
for (int i = 0; i < n; i++)
requests_handled++;
printf("this thread handled %d\n", requests_handled);
return NULL;
}
int main(void)
{
int counts[2] = { 3, 5 };
pthread_t t[2];
for (int i = 0; i < 2; i++) {
pthread_create(&t[i], NULL, worker, &counts[i]);
pthread_join(t[i], NULL);
}
printf("main handled %d\n", requests_handled);
return 0;
}this thread handled 3
this thread handled 5
main handled 0Per-thread counters like this are merged at the end, which scales better than one shared counter that every thread updates.
Naming threads and finding them in tools
A process with ten identical-looking threads is hard to debug. Name them. On Linux, pthread_setname_np sets a name of up to 15 characters that appears in top -H, ps -L, gdb and crash dumps. Rust's thread::Builder::name does the same, and in C++ you set it through native_handle():
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
static void *worker(void *arg)
{
(void)arg;
pthread_setname_np(pthread_self(), "net-rx");
char name[16];
pthread_getname_np(pthread_self(), name, sizeof name);
printf("thread name: %s\n", name);
return NULL;
}
int main(void)
{
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
pthread_join(t, NULL);
return 0;
}thread name: net-rxThe limits and the tools that read the name are in naming threads for debugging. In gdb, info threads lists them by name and thread apply all bt prints every thread's backtrace, which is the first command to run on a hung process.
Controlling where and how threads run
The kernel decides which CPU runs which thread, and the defaults suit most programs. When they do not, three controls exist, each with a post of its own:
| Control | Call | Use it for |
|---|---|---|
| CPU affinity | pthread_setaffinity_np | Keeping a thread on one core for cache locality or isolation |
| Real-time priority | pthread_setschedparam with SCHED_FIFO | Deadline-driven loops, with the privilege to set it |
| Stack size | pthread_attr_setstacksize | Deep recursion or many small threads |
A thread pinned to a core shows its placement with sched_getcpu:
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
int main(void)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(0, &set);
if (pthread_setaffinity_np(pthread_self(), sizeof set, &set) != 0)
return 1;
printf("running on cpu %d\n", sched_getcpu());
return 0;
}running on cpu 0Treat all three as measured optimizations. Pinning threads lists the cases where pinning loses to the scheduler, real-time priorities covers the permission model and priority inversion, and stack sizing shows how to size by reasoning rather than guessing.
From threads to a thread pool
Creating a thread per task does not scale: each one costs a stack and a kernel task, and thousands of threads thrash the scheduler. The standard answer is a pool of workers fed from a queue. The C skeleton uses a mutex, a condition variable and a queue, and it is built in full in the thread pool post. The essential loop is:
static void *worker_main(void *arg)
{
struct pool *p = arg;
for (;;) {
pthread_mutex_lock(&p->lock);
while (p->head == NULL && !p->shutting_down)
pthread_cond_wait(&p->wake, &p->lock);
if (p->head == NULL) {
pthread_mutex_unlock(&p->lock);
return NULL;
}
struct task *t = p->head;
p->head = t->next;
pthread_mutex_unlock(&p->lock);
t->fn(t->arg);
free(t);
}
}The while re-checks the predicate because wake-ups can be spurious, and the task runs outside the lock so the workers truly run in parallel. In C++ the standard library has no pool in C++20, and in Rust the rayon crate provides one. The principle carries across: bound the number of threads, and queue the rest.
Sharing data safely: the smallest useful lock
The race above has two fixes, and the mutex is the one every language shares. A mutex lets one thread at a time into a region of code. Everything between lock and unlock is a critical section, and two critical sections guarded by the same mutex never overlap. Here is the counter in C, repaired:
#include <pthread.h>
#include <stdio.h>
static long counter;
static pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER;
static void *bump(void *arg)
{
(void)arg;
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&counter_lock);
counter++;
pthread_mutex_unlock(&counter_lock);
}
return NULL;
}
int main(void)
{
pthread_t a, b;
pthread_create(&a, NULL, bump, NULL);
pthread_create(&b, NULL, bump, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("counter = %ld\n", counter);
return 0;
}counter = 2000000Now the loop is correct, and the answer is the same on every run. The cost is that every increment takes and releases a lock, and when two threads collide, one of them sleeps in the kernel. For a counter, an atomic is cheaper, and the atomics guide shows how. For anything larger than one machine word, such as updating two fields together or modifying a list, a mutex is the right tool.
The C++ version uses std::mutex with an RAII guard, so the unlock cannot be forgotten, even if an exception is thrown:
#include <iostream>
#include <mutex>
#include <thread>
int main()
{
long counter = 0;
std::mutex lock;
auto bump = [&] {
for (int i = 0; i < 1000000; ++i) {
std::lock_guard guard(lock);
++counter;
}
};
{
std::jthread a(bump);
std::jthread b(bump);
}
std::cout << "counter = " << counter << '\n';
}counter = 2000000The inner braces end the scope and so join both threads before the read. Rust goes one step further and ties the data to the lock. A Mutex<T> owns the value it protects, and the only way to reach the value is through the guard that lock() returns:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0u64));
let handles: Vec<_> = (0..2)
.map(|_| {
let counter = Arc::clone(&counter);
thread::spawn(move || {
for _ in 0..1_000_000 {
*counter.lock().unwrap() += 1;
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
println!("counter = {}", *counter.lock().unwrap());
}counter = 2000000You cannot forget to lock in Rust, because there is no other path to the integer. Arc provides shared ownership across threads, and lock() returns a Result because a thread that panicked while holding the lock leaves the mutex "poisoned", a signal that the data may be inconsistent. C and C++ have no equivalent flag, so after a thread dies holding a lock, the next thread proceeds.
Three rules cover most lock bugs. Hold a lock for as short a time as possible. Never call unknown code (a callback, a virtual function) while holding one. And when you need two locks, always take them in the same order everywhere, or two threads will each hold one and wait for the other, which is a deadlock.
Waiting for something: condition variables and channels
A mutex answers "who may touch this now". It does not answer "wait until there is something to touch". Polling a flag in a loop burns a CPU, and sleeping for a fixed time wastes latency. A condition variable lets a thread sleep until another thread signals that a condition holds. The condition itself lives in shared data protected by the mutex, and the waiting thread always re-checks it in a loop. Here is a one-slot handoff in C++:
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <optional>
#include <thread>
int main()
{
std::mutex m;
std::condition_variable ready;
std::optional<int> slot;
std::jthread consumer([&] {
std::unique_lock lock(m);
ready.wait(lock, [&] { return slot.has_value(); });
std::cout << "consumer got " << *slot << '\n';
});
{
std::lock_guard lock(m);
slot = 42;
}
ready.notify_one();
}consumer got 42The predicate form of wait is the loop: it rechecks the condition after every wake-up and handles the case where the producer set the value before the consumer started waiting. Writing wait(lock) without a predicate and without a loop is the most common cause of lost wake-ups.
Rust offers the same primitive in Condvar, and also a higher-level tool that most programs should reach for first: a channel. A channel moves a value from one thread to another and hides the lock and the condition variable inside it:
use std::sync::mpsc;
use std::thread;
fn main() {
let (sender, receiver) = mpsc::channel();
let producer = thread::spawn(move || {
for n in 1..=3 {
sender.send(n * 10).unwrap();
}
});
for value in receiver {
println!("received {value}");
}
producer.join().unwrap();
}received 10
received 20
received 30The loop over receiver ends when every sender has been dropped, which happens when the producer thread finishes. That turns "how do I tell the consumer there is no more work" into a property of ownership. The C equivalent is a queue guarded by a mutex and a condition variable, which is what the thread pool earlier in this guide is built from.
A complete worked example: counting lines in parallel
Here is the whole lifecycle in one realistic program: split a job into parts, give each thread its own input and output, join, and combine. The task is to count the lines in several buffers. We use C, then show how the same shape looks in Rust.
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#define PARTS 4
struct part {
const char *text; /* input */
size_t lines; /* output */
};
static void *count_lines(void *arg)
{
struct part *part = arg;
size_t n = 0;
for (const char *p = part->text; *p != '\0'; p++)
if (*p == '\n')
n++;
part->lines = n;
return NULL;
}
int main(void)
{
const char *texts[PARTS] = {
"alpha\nbeta\n",
"gamma\n",
"delta\nepsilon\nzeta\n",
"",
};
struct part parts[PARTS];
pthread_t threads[PARTS];
for (int i = 0; i < PARTS; i++) {
parts[i].text = texts[i];
parts[i].lines = 0;
int rc = pthread_create(&threads[i], NULL, count_lines, &parts[i]);
if (rc != 0) {
fprintf(stderr, "pthread_create: %s\n", strerror(rc));
return 1;
}
}
size_t total = 0;
for (int i = 0; i < PARTS; i++) {
pthread_join(threads[i], NULL);
printf("part %d: %zu lines\n", i, parts[i].lines);
total += parts[i].lines;
}
printf("total: %zu lines\n", total);
return 0;
}part 0: 2 lines
part 1: 1 lines
part 2: 3 lines
part 3: 0 lines
total: 6 linesNotice how the design avoids every hazard discussed so far. The inputs are read-only string literals with static storage. Each thread writes only to its own part. The joins happen in order in the main thread, which prints after each, so the output order is fixed. There is no lock because there is no sharing. This is the pattern to reach for first: partition the data, compute independently, merge after the join.
The Rust version expresses the same partition with scoped threads, so the compiler checks the borrowing:
use std::thread;
fn main() {
let texts = ["alpha\nbeta\n", "gamma\n", "delta\nepsilon\nzeta\n", ""];
let counts: Vec<usize> = thread::scope(|s| {
let handles: Vec<_> = texts
.iter()
.map(|text| s.spawn(move || text.matches('\n').count()))
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
for (i, n) in counts.iter().enumerate() {
println!("part {i}: {n} lines");
}
println!("total: {} lines", counts.iter().sum::<usize>());
}part 0: 2 lines
part 1: 1 lines
part 2: 3 lines
part 3: 0 lines
total: 6 linesEach closure returns the count, and join() brings it back, so there is no output slot to manage. When the pieces are not equal in size, a fixed number of threads fed from a queue balances the load better than one thread per piece.
Threads and the rest of the process
A thread does not live alone. Several process-wide facilities interact with threads in ways that surprise people.
Signals. A signal sent to a process is delivered to one thread that does not block it, chosen by the kernel. Each thread has its own signal mask, set with pthread_sigmask, and the common practice is to block all signals in every thread except one dedicated signal-handling thread, which waits with sigwait. Directed signals go to a specific thread with pthread_kill. See the series on signals in multithreaded programs for the details.
fork. Calling fork in a multithreaded program creates a child with exactly one thread, a copy of the caller. Locks held by other threads at that instant stay locked forever in the child, because nobody exists to release them. The child may only call async-signal-safe functions until it calls exec. Libraries that need to survive a fork register pthread_atfork handlers, and the rule of thumb is to avoid forking from a threaded program except to exec immediately.
Exit. exit or returning from main ends the process and kills every thread, in the middle of whatever it was doing. pthread_exit from the main thread ends only that thread and lets the process continue until the last thread finishes. Calling exit from a thread while others are running destructors for static objects can race with those threads still using them, which is a classic source of crashes at shutdown.
Working directory and credentials. The current directory, umask and open files are shared, so a chdir in one thread affects all of them. Linux also keeps per-thread credentials at the kernel level, but glibc synchronizes setuid across threads so the process behaves uniformly.
Memory allocation. malloc and free are thread-safe in glibc, which uses per-thread arenas to reduce contention. A block allocated in one thread may be freed in another, though that can cost performance with some allocators and is worth avoiding in hot paths.
Portability: POSIX, Windows and the standard libraries
The pthreads interface is POSIX and runs on Linux, macOS and the BSDs. Windows has its own thread API (CreateThread, with a different lifecycle model and no fork), and C programs that must run on both use a wrapper or C11 <threads.h>. The standard C++ and Rust libraries hide the difference and call the native API underneath, which is the main reason to use them over raw pthreads when you do not need the extras.
A few differences matter in practice:
| Feature | Linux (glibc) | macOS | Windows |
|---|---|---|---|
| Thread name | pthread_setname_np(thread, name), 15 chars | pthread_setname_np(name), caller only | SetThreadDescription |
| CPU pinning | pthread_setaffinity_np | Affinity tags only, no pinning | SetThreadAffinityMask |
| Default stack | RLIMIT_STACK, often 8 MiB | 512 KiB for secondary threads | 1 MiB, set at link time |
| Real-time priority | SCHED_FIFO with privilege | Thread policies via Mach | Priority classes |
fork | Yes | Yes | No |
The C11 <threads.h> interface offers thrd_create, thrd_join, mtx_lock and cnd_wait. It is optional in the standard (check __STDC_NO_THREADS__), is implemented in glibc 2.28 and later as a thin layer over pthreads, and lacks names, affinity, priorities and attributes. Use it when portability matters more than control.
Reading a hung program with gdb
When a threaded program hangs, the first move is to look at every thread. Attach to the process and print all backtraces:
gdb -p 5120
(gdb) thread apply all btA deadlock between two threads looks like this in the output, abridged:
Thread 3 (Thread 0x7f0e3b7fe640 (LWP 5123) "worker-b"):
#0 0x00007f0e3c5290ec in __lll_lock_wait () from /lib/x86_64-linux-gnu/libc.so.6
#1 0x00007f0e3c52f9d0 in pthread_mutex_lock () from /lib/x86_64-linux-gnu/libc.so.6
#2 0x000055d4a1c0a2f1 in transfer (from=0x55d4a1c0d060 <account_a>, ...) at bank.c:31
Thread 2 (Thread 0x7f0e3bfff640 (LWP 5122) "worker-a"):
#0 0x00007f0e3c5290ec in __lll_lock_wait () from /lib/x86_64-linux-gnu/libc.so.6
#1 0x00007f0e3c52f9d0 in pthread_mutex_lock () from /lib/x86_64-linux-gnu/libc.so.6
#2 0x000055d4a1c0a2f1 in transfer (from=0x55d4a1c0d0a0 <account_b>, ...) at bank.c:31The addresses are illustrative. The pattern is what matters: both threads are blocked in __lll_lock_wait, the low-level lock wait, called from pthread_mutex_lock at the same source line, each holding the lock the other wants. The thread names, set earlier with pthread_setname_np, make the listing readable. In gdb, print *mutex on a glibc mutex shows its __owner field, the TID of the holder, which tells you exactly which thread to look at.
For a thread that is not blocked but spinning, thread apply all bt shows it in user code, and top -H -p 5120 shows which thread uses the CPU. For races and misuse, the sanitizers are the tool, and Valgrind's helgrind and drd tools check lock ordering and unsynchronized access without recompiling.
Common design patterns for thread use
Most threaded programs are built from a handful of shapes. Knowing the names helps you pick one deliberately.
Fork and join. The creator splits work, starts threads, and joins them all, as in the line counter. It suits data-parallel jobs where the pieces are independent and the creator waits for the answer. Rust's thread::scope and C++'s std::jthread in a scope encode it.
Worker pool. A fixed set of threads takes tasks from a shared queue, as in the pool above. It suits many short tasks arriving over time, such as requests.
Pipeline. Threads form stages connected by queues: read, parse, transform, write. Each stage runs in its own thread, so the stages overlap, and the slowest stage sets the throughput. Bounded queues between stages give back-pressure, so a fast producer cannot flood a slow consumer.
Dedicated thread for a job. One thread owns a resource that must be touched from one place: a GUI, a database connection with thread affinity, a signal handler, a log file writer. Other threads send it messages instead of touching the resource.
Background service thread. A long-lived thread does periodic work, such as flushing a cache, and is stopped at shutdown with a stop token or a flag, then joined.
Choose by the question each answers: who owns the data, who waits for whom, and who decides when it ends. If you cannot answer all three for a design, simplify it before writing the code.
What can go wrong: a field guide
Threads fail in a few recurring ways. Learn the symptoms:
| Bug | Symptom | First tool |
|---|---|---|
| Data race | Wrong results that change run to run; works in debug, fails in release | ThreadSanitizer (-fsanitize=thread) |
| Deadlock | Program hangs, CPU near zero | gdb, thread apply all bt |
| Use after free | Crash in a thread long after the data was freed | AddressSanitizer (-fsanitize=address) |
| Leak of joinable threads | Memory grows with thread count | /proc/<pid>/maps, count of mappings |
| Lost wake-up | A thread waits forever for a signal that came earlier | Review predicate and lock use |
| Stack overflow | SIGSEGV in a deep call chain | Core dump, guard page address |
A data race is the one that does the most damage, because it is undefined behavior in C and C++ and the compiler is free to assume it never happens. Here is a counter incremented by two threads without protection:
#include <pthread.h>
#include <stdio.h>
static long counter;
static void *bump(void *arg)
{
(void)arg;
for (int i = 0; i < 1000000; i++)
counter++; /* data race */
return NULL;
}
int main(void)
{
pthread_t a, b;
pthread_create(&a, NULL, bump, NULL);
pthread_create(&b, NULL, bump, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("counter = %ld (expected 2000000)\n", counter);
return 0;
}counter = 1374562 (expected 2000000)The printed number is an example. It will differ on every run and may occasionally equal the expected value, which is part of what makes races hard to find. The cause is that counter++ is a read, an add and a write, and two threads interleave those steps and lose updates. Compile with gcc -fsanitize=thread -g -pthread race.c and run it, and ThreadSanitizer reports a data race with both stack traces:
WARNING: ThreadSanitizer: data race (pid=31337)
Write of size 8 at 0x000000601040 by thread T2:
#0 bump race.c:9
Previous write of size 8 at 0x000000601040 by thread T1:
#0 bump race.c:9The report format is from the sanitizer; addresses and process IDs vary. The fix is a lock or an atomic, both covered by the next clusters. In Rust the same program does not compile, because mutating a static mut needs unsafe and a plain captured &mut cannot go to two threads: the compiler stops the bug before it exists. That asymmetry is the strongest argument for Rust in threaded code, and it has a price: you must express your sharing in the type system.
What a join guarantees about memory
Why can main read jobs[i].sum safely after the join, without a lock? Because every threading API defines certain operations as synchronization points that order memory accesses. Starting a thread, joining it, locking and unlocking a mutex, and signalling and waiting on a condition variable are all such points. POSIX states that these functions synchronize memory with respect to other threads, and the C11, C++11 and Rust memory models say the same in their own words: thread creation happens-before the first action of the new thread, and a thread's last action happens-before the return of a join on it.
That gives you two rules to lean on without any further machinery:
Anything the creator wrote before
pthread_create(orspawn, or thestd::threadconstructor) is visible to the new thread when it starts. That is why you can fill a struct and pass its address.Anything a thread wrote before it ended is visible to the thread that joins it. That is why reading the output slot after the join is safe.
Between those two points, if two threads touch the same memory and at least one writes, you need another synchronization point. A plain variable that one thread sets and another polls is a data race even if it "works on your machine", because the compiler may keep the value in a register and never reread it, and the hardware may delay the store. The fix is an atomic or a lock, and the details of why are the subject of the memory-ordering cluster.
#include <pthread.h>
#include <stdio.h>
static int config_value; /* written before create, read by the thread */
static int result_value; /* written by the thread, read after join */
static void *worker(void *arg)
{
(void)arg;
result_value = config_value * 2;
return NULL;
}
int main(void)
{
config_value = 21; /* happens-before the thread's first action */
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
pthread_join(t, NULL); /* the thread's last action happens-before this */
printf("result = %d\n", result_value);
return 0;
}result = 42Both variables are plain ints with no lock, and the program is correct because the only cross-thread accesses are ordered by create and join. Add a second thread that writes config_value while the worker reads it, and the program has a race.
What threads cost and what they buy
Threads are a trade, and it helps to name both sides without inventing numbers. The mechanism tells you where the costs are.
Creation. A new thread needs a stack mapping, a thread descriptor and a kernel task. glibc caches the stacks of finished threads, so repeated creation is cheaper than the first. Creation and join still enter the kernel, so a design that starts a thread for a microsecond of work spends more on creation than on the work.
Memory. Each thread reserves address space for its stack (commonly 8 MiB) and touches only the pages it uses. The resident cost is small, but the reserved address space and the number of mappings are limits, and a process with a very large thread count can hit vm.max_map_count or a cgroup pids.max before it runs out of RAM.
Scheduling. More runnable threads than cores means the kernel time-slices, and each switch costs a kernel entry and a cache-cold start for the thread resumed. The cost is measurable on your hardware with the method in measuring context switch costs.
Contention. A lock that every thread takes serializes them. Adding threads to a program dominated by one lock makes it slower, because the threads now also pay for the lock handoffs. This is the commonest reason a parallel version loses to the serial one.
Cache effects. Two threads writing to different variables that sit on one cache line fight for ownership of that line, a problem known as false sharing. It looks like a lock-free design that scales badly, and padding or splitting the data fixes it.
What you buy. Threads buy overlap, since one thread can wait on I/O while another computes, and parallelism, since several cores run at once. The expected speedup of the parallel part is bounded by Amdahl's law: if a fraction of the work must run serially, no thread count removes it. The honest procedure is to measure the serial program, find the fraction that parallelizes, estimate the bound, and then measure the threaded one.
A quick way to see whether threads are helping is perf stat:
perf stat -e task-clock,context-switches,cpu-migrations ./app Performance counter stats for './app':
3,812.40 msec task-clock # 3.521 CPUs utilized
12,044 context-switches
7 cpu-migrationsThe numbers are an illustration of the report's shape. "CPUs utilized" near the number of threads you started means they are really running in parallel. A value near 1 with many threads means they are mostly waiting, which points to a lock or I/O bottleneck rather than a lack of cores.
A review checklist for thread code
Before merging code that starts threads, walk through these questions. Each one catches a class of bug from earlier in this guide.
Who ends each thread, and when? Name the join, detach or stop for every thread. If there is none, there is a leak or an abort.
What does each thread touch? List the memory it reads and writes. Anything written by one thread and touched by another needs a lock, an atomic or a join to order it.
How do errors travel? A creation failure, a worker error, an exception or a panic must end up somewhere that can act on it.
Is the creation error checked?
pthread_createreturns a value, andspawnmay panic; both can fail in production when limits are hit.Are arguments owned correctly? No address of a loop variable, no pointer to a stack frame that may die first, no
std::refof a temporary.Are locks taken in one order? If two locks are ever held together, the order must be the same on every path.
Does the thread have a name? A named thread is a debuggable thread.
What is the stack budget? Large local arrays and deep recursion need either a measured stack size or a heap allocation.
Does shutdown work? Start the program, ask it to stop, and confirm every thread joins. Test it, since shutdown races are common.
Did a sanitizer run? ThreadSanitizer on a stress test finds the races that review misses.
None of these is specific to a language. They are the questions that decide whether a threaded program stays correct as it changes, and answering them in a comment next to the thread creation is cheap insurance.
Testing thread code
Concurrent code needs tests that are repeatable and tools that find bugs the tests miss.
Run the sanitizers in CI. ThreadSanitizer for races and AddressSanitizer for memory errors, in separate builds, since they cannot combine.
Stress it. Run the test hundreds or thousands of times, with more threads than cores, so interleavings vary. A race that appears once in a million is still a bug.
Make order explicit. Use latches, barriers and semaphores to force the interleaving you want to test instead of sleeping and hoping.
Model-check small cores. For lock-free code, tools like
loomin Rust explore interleavings exhaustively.Keep thread code small. Put the concurrency in one module with a narrow interface, and test the logic single-threaded.
A sleep-based test is a flaky test waiting to happen. Replace sleep(1) with a signal that says what you are waiting for.
Choosing between the three languages
| Question | C | C++ | Rust |
|---|---|---|---|
| Who frees thread resources? | You, by joining or detaching | jthread destructor, or you | JoinHandle drop detaches |
| Are races a compile error? | No | No | Yes, for safe code |
| Is there a stop mechanism? | A flag you write | stop_token | A flag or channel |
| Portability | POSIX, or C11 <threads.h> | Standard library | Standard library |
| Scoped borrowing | Manual discipline | Manual discipline | thread::scope |
| Where exceptions go | Return codes | Must capture | join() returns Err |
Pick the language by the whole project, not by the threading API. If you are writing a kernel module or a driver, threads are kthreads and an entirely different API applies. If you are on a microcontroller, you want an RTOS task API. If you are writing a network service in Rust, an async runtime may serve better than raw threads.
When threads are not the answer
Threads are not free, and they are not the only way to do two things at once.
Waiting on many sockets. An event loop with
epollhandles tens of thousands of idle connections in one thread; a thread per connection would spend its stack and scheduler time on nothing.Splitting CPU work. A fixed pool sized to the CPU count, or a data-parallel library, uses cores without oversubscribing them.
Isolation. If one task must not be able to corrupt another, use a process. A crash in a thread takes down all of them.
Simplicity. If the work is fast enough in one thread, one thread is the correct design. Concurrency adds testing cost forever.
Measure before parallelizing. A workload that is memory-bound or contends on one lock gains nothing from more threads, and a design that scales to eight cores on paper may scale to two.
Where to go next in the cluster
This guide covers the lifecycle. The rest of the Concurrency topic builds on it in order. Atomics and memory ordering, the next cluster, explains how threads can share a variable without a lock, starting with the guide to atomics and memory ordering. Locks and condition variables cover the blocking synchronization used by the thread pool above. Lock-free structures and RCU come after that, and the neighboring Systems Programming and Kernels topics cover the signals, futexes and scheduler that sit under all of it.
The expert posts in this cluster open the box: thread stacks and guard pages, measuring context switch cost, and the Go scheduler as a counterpoint to one-to-one OS threads.


