Authors: Denis Kozadaev, Sergey Lyubka. June 2007. English edition: Rob Ewaschuk, April 2008. What is a mutex and how does it work? Imagine a big office (your program), with many assets (shared resources) and many employees (threads). For example, all employees share one common resource - a toilet. All employees have agreed to use a label on a toilet's door (mutex). When an employee wants to use a toilet, he checks a label on a door (locks a mutex): if it is "engaged", he waits (blocks on a mutex), then when it is "free", he enters the toilet and changes the label to "engaged" (mutex lock succeeded). When an employee has finished his business in the toilet, he goes out and changes the label to "free" (unlocks the mutex). If there are many people in the office, there may even be a queue (many threads blocked on a mutex). Then it is up to a manager (thread implementation algorithm), who is allowed to enter the toilet next. Usually, it is the first person to arrive into the queue (FIFO algorithm). So, in order to pee safely, following rules must apply: 1. Everybody who wants to pee, MUST use a label - enter only when it is "free" and set the label to "engaged" (lock mutex). Otherwise confusion guaranteed. 2. After peeing, the label must be set to "free" (unlock mutex). These rules, as you see, are just an agreement in the office (program logic). The label on a toilet's door (a mutex) and a toilet itself (a resource) are totally independent. The label can be anywhere, for example, at the helpdesk. The main thing is that everybody knows where it is and how it should be used. What happens if somebody in the office does not follow the agreement (some thread does not use mutex when accessing a resource)? That person enters the toilet paying no attention to the label. Somebody may be there already, and as you can imagine, bad things may happen.