The task of guaranteeing that only one of several
processes enters the same critical section. Forgetting mutual
exclusion may lead to race conditions, which are difficult to find
bugs. There are several methods to achieve mutual exclusion:
- Mutex variable:
- One (or several) variables which are
counted up/down or are changed by some specific algorithm (e.g.
Bakery algorithm) to reach mutual exclusion. With the current
hardware support of atomic test&set operations these are easy to
implement.
- Semaphore:
- A counter set to a starting number, which
can be hold by exactly that number of processes. More processes can
only get hold of the semaphore if earlier processes given it up.
Internally often uses a mutex variable.
- Monitor:
- A section of code (sometimes also an
object), which by itself allows only one process to enter it. Within
the monitor, processes can decide to wait for some conditions which
allows another process to enter the monitor. Java's "synchronized"
construct can be seen as a monitor.
Each method for mutual exclusion can be implemented
using another one as basis.