Why it matters

Locks are the workhorse of shared-state concurrency. Getting them right prevents most concurrency bugs.

Advertisement

The architecture

Acquire: try to take lock. If free, take. If held, block.

Release: give up lock. Wakes waiting thread.

Lock varietiesSpin lockbusy wait, fastBlocking locksleep, generalReentrant locksame thread OKSpin for very short critical sections; blocking for anything longer
Lock types.
Advertisement

How it works end to end

Spin lock: busy waits. Fast when contention is low and hold time is very short. Wastes CPU otherwise.

Sleeping lock: OS puts thread to sleep, wakes when lock released. General purpose.

Reentrant lock: same thread can acquire multiple times without deadlocking with itself.

Try-lock: attempt to acquire with timeout. Enables deadlock avoidance patterns.