wiki: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; }
wiki/h-threads.md · Last modified: by 127.0.0.1
