Lesson 40 of 50 · c
Multithreading with `<threads.h>` (C11)
Duration: 15 mins
C11 introduced a portable threading API: thrd_t, mtx_t, cnd_t etc., from <threads.h>.
Typical workflow:
- Create a thread with
thrd_create(&t, func, arg);. - Wait for it to finish with
thrd_join(t, &ret);. - Protect shared data with a mutex (
mtx_lock,mtx_unlock).
mtx_t lock;
mtx_init(&lock, mtx_plain);
mtx_lock(&lock);
/* critical section */
mtx_unlock(&lock);
The API is intentionally minimal – for more advanced needs use POSIX threads (pthread) on Unix or Win32 threads on Windows.