typestar

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.

Start this tour

Starting threads

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

Encore

  • thread_pool.cA fixed pool of workers pulling jobs off a shared queue until it closes.

The other C tours