Mutual Exclusion
Mutual Exclusion: A synchronization technique that restricts multiple processes or threads from accessing shared resources simultaneously.
Mutual Exclusion Technique
Mutual Exclusion is a technique that ensures that when multiple execution flows access the same shared resource, only one execution flow can use the resource at a time.
If multiple threads access the same variable, file, memory area, kernel object, etc. at the same time, the results may vary depending on the execution order.
This problem is called Race Condition.
Mutual Exclusion protects code areas that access shared resources to prevent race conditions.
At this time, the code area that accesses the shared resource is called the Critical Section.
counter++;
The above C language code is a code that increases the counter value by 1.
However, in reality, it is not a single action, but rather a series of steps.
mov eax, DWORD PTR [counter]
add eax, 1
mov DWORD PTR [counter], eax
In other words, the counter value is read from memory, 1 is added, and stored again in memory.
If two threads execute this code at the same time, problems may occur.
Sequence Thread 1 Thread 2 counter
| 1 | read counter | 0 | |
| 2 | read counter | 0 | |
| 3 | 1 plus | 0 | |
| 4 | 1 plus | 0 | |
| 5 | save counter | 1 | |
| 6 | save counter | 1 |
Since both threads each increment the counter by 1, the result should be 2.
However, because both threads read the same value, 0, and each stored 1, the result can be 1.
In other words, simultaneous access to shared resources may not produce the intended results.
Mutual Exclusion allows only one execution flow to enter the Critical Section at the same time to prevent this situation.