FastNetMon

вторник, 21 августа 2007 г.

Мьютексы

What is a mutex and how does it work?

Imagine a big office (your program), with many assets (shared resources)
and many employees (threads). As an example, all employees share one common
resource - a toilet. All employees have agreed to use a label on a
toilet's door (mutex).

When 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 employee had finished his business
in the toilet, he goes out and changes the label to "free" (unlocks mutex).

If there are many people in the office, it even may be a queue (many threads
blocked on a mutex). Then it is up to a manager (threads implementation
algorithm), who gonna enter the toilet next. Usually, it is the first person
in 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, is just an agreement in the office (program logic).
The label on the toilet's door (mutex) and a toilet itself (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 sitting
there already, and as you can imagine, BAD things may happen.

Authors: Denis Kozadaev, Sergey Lyubka. June 2007.


От себя добавлю, что это лучшее и наиболее наглядное описание принципа работы мьютексов из виденных мною.

Комментариев нет :

Отправка комментария

Примечание. Отправлять комментарии могут только участники этого блога.