However, the above code will not work correctly, it will violate mutual exclusion . Mutual exclusion is the principle that only one process can access the critical section at any one time. Whenever a process is tasked-out between the lock test and the lock set, there is a good chance that mutual exclusion will be violated. Therefore, the lock test and the lock set must be performed in a single, atomic operation. An atomic operation is one that can be completed without being tasked-out.
Algorithms do exist, but large, bulky, and slow.
The OS can control the scheduling of a task and can therefore guarantee that a process will not get interrupted. Semaphores Semaphores are a real-time construct that solve the mutual exclusion problem. The operations of a semaphore are atomic. Just as different OSes implemented different versions of shared memory and message queues , there are several implementations of semaphores. System V also implements semaphores .