Why do we need mutual exclusion?
Mutual exclusion is a fundamental concept in concurrent programming that ensures that multiple threads or processes do not simultaneously access a shared resource such as a shared variable, a critical section of code, or a file or network connection. Mutual exclusion is crucial for preventing race conditions such as the one we have seen in the previous section.
Imagine a small coffee shop with a single espresso machine. The machine can only make one espresso at a time. This means the machine is a critical resource that all baristas must share.
The coffee shop is attended by three baristas: Alice, Bob, and Carol. They use the coffee machine concurrently, but they cannot use it simultaneously because that could create problems: Bob puts the right amount of freshly ground coffee in the machine and starts making an espresso. Then, Alice does the same but first removes the coffee from the machine, thinking that Bob just forgot to do it. Bob then takes...