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




















