Threads & concurrency
10 steps in 4 sets of C.
Threads in C11, plus the mutexes and condition variables that keep them from destroying each other. Then atomics and thread-local storage for the cases where locking is too expensive.
Ten steps. Short, and quietly the most dangerous tour here: nothing in the language will tell you when you have got it wrong.
Starting threads
- Creating threadspthread_create starts a thread running one function; pthread_join waits for it.
- Passing work to a threadOne argument struct per thread, so nothing is shared by accident.
- Detached threadsA detached thread cleans up after itself, and can never be joined.
Locking
- MutexesA mutex serializes access, so two threads never update the counter at once.
- The race you cannot seeThe same increment with and without a lock, run enough times to lose counts.
- Read-write locksMany readers together, or one writer alone.
- Condition variablesA thread waits until another signals that the state it needs has arrived.
Lock-free & local
- C11 atomicsstdatomic gives you a counter that needs no lock at all.
- Thread-local storage_Thread_local gives every thread its own copy of a variable.
Encore
- thread_pool.cA fixed pool of workers pulling jobs off a shared queue until it closes.