liveBook · Manning

Monitor

As explained in Learn Concurrent Programming with Go

A synchronization pattern in which executions check a shared condition while holding a mutex, wait when it is false, and signal or broadcast when the state changes.

A monitor coordinates concurrent executions around shared state: each execution holds a mutex while checking a condition, waits when the condition is false, and signals or broadcasts after changing the state. In Go, the pattern combines a mutex with a condition variable such as sync.Cond. section 5.1.1

Use the monitor pattern by following this cycle:

  • Lock the mutex associated with the condition variable before reading or changing shared state. section 5.1.1
  • Check the condition in a loop; call Wait() when it is false. Wait releases the mutex while suspending and reacquires it before returning. section 5.1.1
  • Call Signal() when a state change may allow another execution to continue, or Broadcast() when all waiting executions should recheck the condition. section 5.1.1 section 5.1.3

Bank balance and multiplayer startup

A spending goroutine locks a sync.Cond, waits while money is below 50, subtracts 50, and unlocks. An earning goroutine adds 10 and signals after each addition, preventing the balance from becoming negative. The same pattern lets player handlers decrement playersRemaining and wait until the final player connects; that handler broadcasts so every waiting goroutine can proceed. section 5.1.1 section 5.1.3

Figure 5.2 Common pattern for using a condition variable with a mutex

Use the synchronization diagram to trace the mutex, condition check, Wait(), and notification cycle. section 5.1.1

How Learn Concurrent Programming with Go covers it

How deep it goes
Explains the pattern through Go implementations using mutexes, Wait(), Signal(), Broadcast(), and mutex reacquisition.
Examples
Uses a shared bank balance and a four-player server waiting for every player to connect.
What it assumes
Builds on mutexes, condition variables, shared state, and goroutines.
What you can do after
Apply it via Go's sync.Cond to coordinate goroutines around changing shared conditions.
How it connects
Connects mutexes, condition variables, goroutines, shared variables, Signal(), Broadcast(), and Wait().

This explainer was generated by Manning's knowledge graph from the text of Learn Concurrent Programming with Go. The section links point to the parts of the book it draws on.