Site Tools


wiki:lock

Lock

A lock is the general term for any mechanism that grants exclusive (or limited) access to a resource shared between threads. Mutex, Spinlock, and reader-writer locks are all locks; they differ in how a thread behaves while waiting and in how many holders are allowed at once. Underneath, every lock is built from the same two ingredients: an atomic read-modify-write instruction to claim ownership without a race, and some policy for what a thread does if it can't claim it right away.

atomic_flag held = ATOMIC_FLAG_INIT;
 
void acquire(void) {
    while (atomic_flag_test_and_set(&held)) {
        /* waiting policy goes here: spin, sleep, or hybrid */
    }
}
 
void release(void) {
    atomic_flag_clear(&held);
}

The waiting policy is the whole design space

A Spinlock busy-waits, retrying the atomic operation in a tight loop until it succeeds. A mutex blocks, handing the core to the OS scheduler and getting woken up later. Which is better depends entirely on expected wait time: spinning wastes CPU cycles but avoids the cost of two context switches, so it wins when the critical section is short and contention is low; blocking wins when waits are long, since burning cycles while asleep helps no one. Many production lock implementations (Linux futexes, for instance) spin briefly first and fall back to blocking, trying to get the better of both regimes without the caller having to choose.

What can go wrong

Locks introduce their own class of bugs that don't exist in single-threaded code. Lock contention describes the throughput cost when too many threads compete for the same lock. Lock convoy describes a specific pathological pattern where contention becomes self-reinforcing. Beyond these, a lock acquired in the wrong order relative to another lock can deadlock two threads against each other permanently, which is why most style guides insist on a fixed, global ordering for acquiring multiple locks at once.

wiki/lock.md · Last modified: by 127.0.0.1