h-threads
Table of Contents
<threads.h>
<threads.h> provides portable threading (C11): thrd_create, thrd_join, mutexes, and condition variables. Linux mainly uses POSIX pthreads instead, since threads.h support was added to glibc only recently (2022).
Use threads.h for new portable C11 code; use pthreads for existing Linux code.
Example
This example creates two threads that increment a shared counter under mutex protection.
// compile: gcc -std=c11 -pthread -o threadsexample threadsexample.c // run: ./threadsexample // description: two threads safely increment a counter under mutex #include <threads.h> #include <stdio.h> mtx_t lock; int counter = 0; int worker(void* arg) { (void)arg; for (int i = 0; i < 100000; i++) { mtx_lock(&lock); counter++; mtx_unlock(&lock); } return 0; } int main() { mtx_init(&lock, mtx_plain); thrd_t t1, t2; thrd_create(&t1, worker, NULL); thrd_create(&t2, worker, NULL); thrd_join(t1, NULL); thrd_join(t2, NULL); printf("counter: %d (expected 200000)\n", counter); mtx_destroy(&lock); return 0; }
Common functions
Thread creation/termination:
thrd_create(&t, func, arg): create threadthrd_join(t, &res): wait for thread to finishthrd_detach(t): detach thread (cleanup automatic)thrd_exit(res): exit thread
Mutex operations:
mtx_init(&m, type): initialize mutexmtx_lock(&m): lock mutexmtx_trylock(&m): try to lock (returns non-zero on success)mtx_unlock(&m): unlock mutexmtx_destroy(&m): destroy mutexmtx_plain: plain mutex (type for mtx_init)mtx_recursive: recursive mutex type
Condition variables:
cnd_init(&c): initialize condition variablecnd_wait(&c, &m): wait on condition (releases mutex)cnd_timedwait(&c, &m, &time): wait with timeoutcnd_signal(&c): wake one waitercnd_broadcast(&c): wake all waiterscnd_destroy(&c): destroy condition variable
Thread-local storage:
thread_local: storage class for thread-local variablestss_create(&key, dtor): create thread-specific storage keytss_set(key, val): set value for keytss_get(key): get value for key
h-threads.md · Last modified: by 127.0.0.1
