liveBook · Manning

Locking

As explained in The Coder Cafe

Mutual exclusion is the condition that prevents more than one thread from accessing a protected resource or code section simultaneously.

Locking protects a shared resource when multiple threads might access it. A mutex—short for mutual exclusion—allows only one thread into a protected resource or section of code at a time. A thread that finds the mutex locked must wait. section 2.3

Using a mutex has three steps:

  • Lock the mutex before accessing the resource. section 2.3
  • Access the resource while holding the lock; other threads attempting to lock it must wait. section 2.3
  • Unlock when finished so another thread can proceed. The thread that locks the mutex is responsible for unlocking it. section 2.3

One room, one key

Think of the mutex as a room key. The person holding it can enter; everyone else waits until the key is returned. A semaphore answers a different need: like a parking lot with several spaces, it permits access up to a set limit rather than giving one thread exclusive access. section 2.3

// Thread 1 code
mutex.Lock()
coffee.price = 10
mutex.Unlock()
// Thread 2 code
mutex.Lock()
print(coffee.price)
mutex.Unlock()

Both the write to coffee.price and the read of it are enclosed by Lock and Unlock calls. This prevents their unsynchronized overlap, but it does not decide which thread goes first: the printed price can still depend on timing. section 2.4

Use a mutex when threads share data and access must be exclusive. Removing a data race does not necessarily make the result deterministic: locking protects each access, while execution order can still vary. Coroutines running within a single thread avoid the separate problem of another thread mutating that shared state. section 2.4 section 2.2

How The Coder Cafe covers it

How deep it goes
Defines mutex ownership and walks through locking, waiting, and unlocking; stops short of implementation internals.
Examples
Uses a room key and a shared price read-and-write example to show exclusion and its limits.
What it assumes
Introduces mutexes through threads and shared resources without requiring a named language or library.
What you can do after
Apply mutex locking to shared reads and writes, while recognizing that execution order can still affect results.
How it connects
Connects mutexes to semaphores, coroutines, data races, and race conditions.

Also explained in

Compare how 21 books explain locking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Coder Cafe. The section links point to the parts of the book it draws on.