Skip to content
Tutorials Center
My learning

Topics

C Reference ยท ctype.h, math.h and others

C threads.h: C11 threads, mutexes and conditions

Reference for the C11 threads.h library: thrd_create and thrd_join, mutexes, condition variables, call_once, thread-specific storage, and how it compares to pthreads.

<threads.h> is the standard C way to run code in several threads. It provides threads (thrd_create, thrd_join), mutual exclusion (mtx_t), condition variables (cnd_t), one-time initialization (call_once) and thread-specific storage (tss_t). The design is close to POSIX threads with shorter names, but it is part of ISO C, so in principle it works wherever the standard library offers it.

Support is not universal. An implementation that lacks threads defines the macro __STDC_NO_THREADS__ and does not provide the header. glibc has provided <threads.h> since version 2.28, and the runner's GCC 15 with glibc 2.28 compiles and runs the examples below. Many Linux programs still use pthreads directly because it offers more features (read-write locks, barriers, thread attributes, cancellation).

C
#include <threads.h>

int worker(void *arg) { return 0; }

thrd_t t;
thrd_create(&t, worker, NULL);
thrd_join(t, NULL);

Try it

C Threads, results and a mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Condition variable, call_once and thread-local data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
#include <threads.h>

int  thrd_create(thrd_t *thr, int (*func)(void *), void *arg);
int  thrd_join(thrd_t thr, int *res);
int  thrd_detach(thrd_t thr);
thrd_t thrd_current(void);        int thrd_equal(thrd_t a, thrd_t b);
int  thrd_sleep(const struct timespec *duration, struct timespec *remaining);
void thrd_yield(void);            [[noreturn]] void thrd_exit(int res);

int  mtx_init(mtx_t *m, int type);    /* mtx_plain, mtx_recursive, mtx_timed (or'ed together) */
int  mtx_lock(mtx_t *m);  int mtx_trylock(mtx_t *m);  int mtx_unlock(mtx_t *m);
int  mtx_timedlock(mtx_t *m, const struct timespec *until);   void mtx_destroy(mtx_t *m);

int  cnd_init(cnd_t *c);  int cnd_wait(cnd_t *c, mtx_t *m);   int cnd_signal(cnd_t *c);
int  cnd_broadcast(cnd_t *c);   int cnd_timedwait(cnd_t *c, mtx_t *m, const struct timespec *until);
void cnd_destroy(cnd_t *c);

void call_once(once_flag *flag, void (*func)(void));    /* flag starts as ONCE_FLAG_INIT */
int  tss_create(tss_t *key, void (*destructor)(void *));  void *tss_get(tss_t key);
int  tss_set(tss_t key, void *value);  void tss_delete(tss_t key);
Name Description
func The thread's start function. It takes a void * and returns an int, which thrd_join stores in *res (pass NULL to ignore it).
mtx_plain, mtx_recursive, mtx_timed Mutex kinds. A recursive mutex can be locked repeatedly by the same thread.
cnd_wait(c, m) Atomically unlocks the locked mutex m, sleeps, and relocks m before returning.
once_flag, ONCE_FLAG_INIT Guards a function so it runs exactly once, however many threads call call_once.

Returns: almost every function returns thrd_success on success, or thrd_error, thrd_nomem, thrd_busy (mtx_trylock on a locked mutex) or thrd_timedout on failure. thrd_current returns the calling thread's handle, thrd_equal returns nonzero if the two handles refer to the same thread.

Errors / undefined behavior: a data race on a plain object that is accessed by two threads without synchronization is undefined behavior. Locking a mutex you already hold (non-recursive), unlocking a mutex you do not hold, joining the same thread twice, joining a detached thread, and destroying a mutex that is locked are all undefined.

Usage notes

  • Check for availability. Portable code tests #ifdef __STDC_NO_THREADS__ and falls back to pthreads or Windows threads. Microsoft's C runtime only added <threads.h> in Visual Studio 2022 17.8.
  • Return type is int, not void *. Thread functions return an int result, unlike pthread_create's void *. To return larger data, write through a pointer in the argument.
  • Arguments must outlive the thread. Passing the address of a local that goes out of scope before the thread reads it is a classic bug. The examples keep ids in main until after thrd_join.
  • Always join or detach. A thread you neither join nor detach leaks its resources. Returning from main ends the whole process, including threads that are still running.
  • Wait in a loop. cnd_wait can wake up without a signal. Check the real condition (ready) in a while loop under the mutex, as shown.
  • Output order. printf from several threads is safe but interleaves unpredictably, so deterministic programs print from one thread or after joining.
  • Missing pieces. There are no read-write locks, barriers, thread priorities, cancellation or thread names in ISO C threads; use POSIX for those. thread_local (C23) and _Thread_local (C11) give per-thread variables without tss_create.
  • Link flags. The runner links with -pthread; on other systems older glibc versions need it too.
  • Atomics. For a single counter or flag, stdatomic.h is lighter than a mutex.
  • Standard version: C11 (optional feature). C23 makes thread_local a keyword and thrd_exit [[noreturn]].