<threads.h> is the C11 header for portable threading. It provides threads (thrd_create, thrd_join), mutexes (mtx_lock), condition variables (cnd_wait), one-time initialization (call_once), and thread-local storage (thread_local).
It replaces platform APIs such as POSIX pthread_create and Windows CreateThread with one standard interface. Support is optional: an implementation without threads defines __STDC_NO_THREADS__.
Remember
#include <threads.h>
int worker(void *arg) { ... return 0; }
thrd_t t;
thrd_create(&t, worker, &data); /* thrd_success on OK */
thrd_join(t, &result);
mtx_t m; mtx_init(&m, mtx_plain);
mtx_lock(&m); ... mtx_unlock(&m); mtx_destroy(&m);
Use
Prefer
Start a thread
thrd_create()
Wait for a thread
thrd_join()
Protect shared data
mtx_lock() / mtx_unlock()
Wait for a condition
cnd_wait() / cnd_signal()
Initialize exactly once
call_once()
Per-thread variable
thread_local
Approach
How to Use threads.h in C
Create threads with a function that takes and returns a value, then join them.
Add #include <threads.h> and compile with -std=c11.
Write a thread function with the signature int fn(void *arg).
Start it with thrd_create and check for thrd_success.
Protect shared variables with a mutex, or use stdatomic.h for simple values.
Call thrd_join for every thread you start.
Piece
Required?
Role
#include <threads.h>
Yes
Declares threads, mutexes, and condition variables
Thread function
Yes
int fn(void *arg); its return value reaches thrd_join
-pthread
Older glibc
glibc builds threads on pthreads; add the flag if the link fails
Pseudocode
Pseudocode
thrd_create(&t, worker, &id) // starts worker(&id) in a new thread
...
thrd_join(t, &result) // waits; result = worker's return value
for each thread:
mtx_lock(&m); shared++; mtx_unlock(&m);
Follow one worker thread and then a mutex-protected counter.
Calculation
main: thrd_create(&t, worker, &id) -> new thread runs worker(&id)
worker: prints, returns id * 10
main: thrd_join(t, &result) -> waits, result = 10
mutex counter (4 threads x 1000 increments):
each increment: mtx_lock -> counter++ -> mtx_unlock
final counter = 4 * 1000 = 4000
Code
C Examples
Compile with gcc file.c -std=c11 -o out (add -pthread if the link fails).
Example 1 — Create and Join a Thread
Run a worker in a new thread and read its return value.
C
#include <stdio.h>
#include <threads.h>
static int worker(void *arg) {
int id = *(int *)arg;
printf("worker %d running\n", id);
return id * 10;
}
int main(void) {
thrd_t t;
int id = 1;
int result = 0;
if (thrd_create(&t, worker, &id) != thrd_success) {
fprintf(stderr, "could not create thread\n");
return 1;
}
thrd_join(t, &result);
printf("worker returned %d\n", result);
return 0;
}
Output
worker 1 running
worker returned 10
How It Works
Thread function. It receives a void * and returns an int.
Create and check.thrd_create returns thrd_success on success.
Join waits.thrd_join blocks until the worker finishes and stores its return value in result.
Keep id alive.id lives in main, which stays active until the join.
Example 2 — Protect a Shared Counter with a Mutex
Four threads increment the same counter; the mutex keeps the total correct.
C
#include <stdio.h>
#include <threads.h>
#define THREADS 4
#define LOOPS 1000
static int counter = 0;
static mtx_t lock;
static int add_many(void *arg) {
int i;
(void)arg;
for (i = 0; i < LOOPS; i++) {
mtx_lock(&lock);
counter++;
mtx_unlock(&lock);
}
return 0;
}
int main(void) {
thrd_t th[THREADS];
int i;
mtx_init(&lock, mtx_plain);
for (i = 0; i < THREADS; i++) {
thrd_create(&th[i], add_many, NULL);
}
for (i = 0; i < THREADS; i++) {
thrd_join(th[i], NULL);
}
mtx_destroy(&lock);
printf("counter = %d\n", counter);
return 0;
}
Output
counter = 4000
How It Works
Initialize the mutex.mtx_init(&lock, mtx_plain) creates a basic lock.
Lock around the update. Only one thread at a time runs counter++.
Join all threads. Every thread finishes before the total is printed.
Correct total. 4 threads × 1000 increments = 4000. Without the mutex the result could be lower.
Example 3 — Run Setup Once and Keep Per-Thread State
Use call_once for one-time initialization and thread_local for a private counter per thread.
C
#include <stdio.h>
#include <threads.h>
static once_flag flag = ONCE_FLAG_INIT;
static thread_local int hits = 0;
static void init_once(void) {
printf("init ran once\n");
}
static int task(void *arg) {
int i;
(void)arg;
call_once(&flag, init_once);
for (i = 0; i < 3; i++) {
hits++;
}
return hits;
}
int main(void) {
thrd_t a, b;
int ra = 0, rb = 0;
thrd_create(&a, task, NULL);
thrd_create(&b, task, NULL);
thrd_join(a, &ra);
thrd_join(b, &rb);
printf("thread results: %d and %d\n", ra, rb);
printf("main thread hits = %d\n", hits);
return 0;
}
Output
init ran once
thread results: 3 and 3
main thread hits = 0
How It Works
call_once. Both threads call it, but init_once runs a single time.
thread_local. Each thread has its own hits, so each counts to 3 independently.
Main is separate. The main thread's own hits is still 0.
Edge Cases & Pitfalls
Threading bugs are timing-dependent, so follow the rules strictly.
join
Join or detach every thread
A thread you neither join nor detach leaks its resources.
race
Shared data needs a lock
Two threads updating one variable without a mutex or atomics is a data race, which is undefined behavior.
life
Keep arguments alive
The pointer passed to thrd_create must stay valid until the thread reads it. Do not pass the address of a changing loop variable.
support
Not available everywhere
glibc 2.28 and newer and musl provide it. macOS and MSVC have historically lacked it, so check __STDC_NO_THREADS__ and your toolchain.
Analysis
Performance & Portability Notes
Approach
Cost
Best for
Thread creation
Costs far more than a function call
Long-running tasks, not tiny jobs
Uncontended mutex
Cheap lock and unlock
Short critical sections
Contended mutex
Threads may sleep and wake
Reduce shared state
Output from several threads can interleave in any order. Use joins and locks instead of sleeps to make behavior deterministic.
Remember
Key Takeaways
Role: standard C11 threads, mutexes, condition variables, and call_once.