---
title: "monitor pattern"
type: concept
related: [Monitor Pattern, Deadlock, Multithreading]
source: https://www.jemoka.com/posts/kbhmonitor_pattern/
confidence: high
status: active
---

monitor pattern is a multithreading pattern to help prevent race conditions and deadlocks.
associate a single lock with a collection of variables (a &ldquo;class&rdquo;), having one lock associated with the group.
any time when you want to access anything in that group, you unlock the mutex associated with the group. meaning, there&rsquo;s only one mutex which can be used to change shared state.
Bridge Crossing There is cars that are crossing a one lane bridge: each car in a thread, they have to coordinate when/where to cross the bridge.
Car can be going east or the west. All cars must be traveling in the same direction. And a car can only go once the coast is clear.
Interface static void cross_bridge_east(size_t carid) { approach_bridge(); // sleeping driveAcross(EAST); // sleeping } static void cross_bridge_west(size_t carid) { approach_bridge(); // sleeping driveAcross(WEST); // sleeping } we need to ensure that, we are sharing a one lane bridge, and they don&rsquo;t collide.
Monitor Pattern REDUCES NUMBER OF PARAMS!
Method for the mutex management system isolated into a single, thread-safe class. All the mutexes, etc., all of the mutex gunk gets isolated into a thread safe instance method of the bridge class.
