There are several cases for a thread attempting to enter a room:
If no room is occupied thread can enter required room
If occupied room is the same as required room it is not empty (otherwise it may be the case when the action is being executed at the moment and it is not allowed to enter) and there no other threads waiting for other rooms (otherwise others may starve as continuous stream of coming threads to currently occupied room can prevent it to be set free) thread can enter it
Otherwise thread must wait
Leaving room requires careful thought as well:
If the thread is not the last one it is free to go
Otherwise it must leave the room and execute exit action while keeping the room occupied to prevent others from entering any room
Once exit action is executed if no other thread is waiting the last one is free to go
Otherwise it must wakeup waiting ones
Waiting and waking part can be done using Monitor.Wait and Monitor.PulseAll. Doing so using single sync object is simple but quite inefficient as every pulse all will wakeup all waiting threads (potentially waiting for different rooms) to see that they are not allowed to enter yet as only single room can be occupied at a time. Instead each room will have its own local sync object to wait and pulse on. This will allow to wake up only threads that are now allowed to enter the room they've been waiting on.
Read more: Chasing state of the art
QR: