C threads.h Header

Beginner
6 min read
Updated: Nov 2026
3 examples
C11

What Is threads.h?

<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);
UsePrefer
Start a threadthrd_create()
Wait for a threadthrd_join()
Protect shared datamtx_lock() / mtx_unlock()
Wait for a conditioncnd_wait() / cnd_signal()
Initialize exactly oncecall_once()
Per-thread variablethread_local

How to Use threads.h in C

Create threads with a function that takes and returns a value, then join them.

  1. Add #include <threads.h> and compile with -std=c11.
  2. Write a thread function with the signature int fn(void *arg).
  3. Start it with thrd_create and check for thrd_success.
  4. Protect shared variables with a mutex, or use stdatomic.h for simple values.
  5. Call thrd_join for every thread you start.
PieceRequired?Role
#include <threads.h>YesDeclares threads, mutexes, and condition variables
Thread functionYesint fn(void *arg); its return value reaches thrd_join
-pthreadOlder glibcglibc 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);

Cheat Sheet

Main groups in threads.h.

NameMeaning
thrd_create, thrd_join, thrd_detachStart, wait for, or release a thread
thrd_current, thrd_equal, thrd_exitIdentify or end the current thread
thrd_sleep, thrd_yieldPause or give up the processor
mtx_init, mtx_lock, mtx_trylock, mtx_unlock, mtx_destroyMutex lifecycle
mtx_plain, mtx_recursive, mtx_timedMutex types
cnd_init, cnd_wait, cnd_signal, cnd_broadcastCondition variables
call_once, once_flag, ONCE_FLAG_INITRun an initializer exactly once
thread_local, tss_createThread-specific storage
thrd_success, thrd_error, thrd_busy, thrd_nomem, thrd_timedoutResult codes

Worked Walkthrough — Create, Lock, Join

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

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;
}

How It Works

  1. Thread function. It receives a void * and returns an int.
  2. Create and check. thrd_create returns thrd_success on success.
  3. Join waits. thrd_join blocks until the worker finishes and stores its return value in result.
  4. 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;
}

How It Works

  1. Initialize the mutex. mtx_init(&lock, mtx_plain) creates a basic lock.
  2. Lock around the update. Only one thread at a time runs counter++.
  3. Join all threads. Every thread finishes before the total is printed.
  4. 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;
}

How It Works

  1. call_once. Both threads call it, but init_once runs a single time.
  2. thread_local. Each thread has its own hits, so each counts to 3 independently.
  3. 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.

Performance & Portability Notes

ApproachCostBest for
Thread creationCosts far more than a function callLong-running tasks, not tiny jobs
Uncontended mutexCheap lock and unlockShort critical sections
Contended mutexThreads may sleep and wakeReduce shared state

Output from several threads can interleave in any order. Use joins and locks instead of sleeps to make behavior deterministic.

Key Takeaways

  • Role: standard C11 threads, mutexes, condition variables, and call_once.
  • Pattern: thrd_create, do work, then thrd_join.
  • Safety: lock shared data or use stdatomic.h.
  • Portability: optional; check __STDC_NO_THREADS__.

One line: threads.h is the standard way to start threads and protect shared data in C11.

Frequently Asked Questions

threads.h is the C11 header for portable threads, mutexes, condition variables, one-time initialization, and thread-local storage.
Call thrd_create(&t, fn, arg) where fn has the signature int fn(void *), then call thrd_join(t, &result) to wait for it.
It returns thrd_success on success and stores the thread function's return value through its second argument, which may be NULL.
Yes, or use an atomic type from stdatomic.h. Plain increments from several threads are a data race.
glibc 2.28 and newer and musl support it. macOS has not shipped it, and MSVC support has been limited. Check __STDC_NO_THREADS__.
A storage class macro for _Thread_local. Each thread gets its own copy of the variable.

Next: time.h

Read the clock and format dates with time, localtime, and strftime.

time.h tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful