0 day streak
6. ConcurrencyLocks, semaphores, condition variables

Locks, semaphores, condition variables

Locks, semaphores and condition variables are the basic tools threads use to take turns safely. A lock, or mutex, guards a piece of code so only one thread can be inside at a time, like the single bathroom key at a café. A semaphore is a counter that lets up to n threads in at once, handy for limiting use of a connection pool. A condition variable lets a thread sleep until some condition might be true, such as “the queue isn’t empty”, and be woken by whoever changed it. It’s always paired with a lock, and the waiter re-checks the condition in a loop, since wakeups can be spurious or another thread may get there first.

In this lesson: Step visuals on the same timeline engine.