Site Tools


h-threads

<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 thread
  • thrd_join(t, &res): wait for thread to finish
  • thrd_detach(t): detach thread (cleanup automatic)
  • thrd_exit(res): exit thread

Mutex operations:

  • mtx_init(&m, type): initialize mutex
  • mtx_lock(&m): lock mutex
  • mtx_trylock(&m): try to lock (returns non-zero on success)
  • mtx_unlock(&m): unlock mutex
  • mtx_destroy(&m): destroy mutex
  • mtx_plain: plain mutex (type for mtx_init)
  • mtx_recursive: recursive mutex type

Condition variables:

  • cnd_init(&c): initialize condition variable
  • cnd_wait(&c, &m): wait on condition (releases mutex)
  • cnd_timedwait(&c, &m, &time): wait with timeout
  • cnd_signal(&c): wake one waiter
  • cnd_broadcast(&c): wake all waiters
  • cnd_destroy(&c): destroy condition variable

Thread-local storage:

  • thread_local: storage class for thread-local variables
  • tss_create(&key, dtor): create thread-specific storage key
  • tss_set(key, val): set value for key
  • tss_get(key): get value for key
h-threads.md · Last modified: by 127.0.0.1