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
Use the synchronization diagram to trace the mutex, condition check, Wait(), and notification cycle. section 5.1.1
