Process synchronization #
Race condition #
Critical section and mutual exclusion #
In the above code examples, the counter++
and counter--
are considered a critical section.
How to implement mutual exclusion #
Note: This solution isn’t fully correct.
producer:
while (lock == 0)
lock = 1
put
lock = 0
consumer:
while (lock == 0)
lock = 1
fetch
lock = 0
The problem with this code is that if the OS does a context switch during a critical section, it can create an error.
One solution is to disable interrupts.
Sync hardware, spin locks and compare-and-swap #
Mutex locks #
Mutex locks allow the OS to provide a mutual exclusion as a service.
Semaphores #
A semaphore is simply a non-negative interger that has two valid operations.