Before you go through this article, make sure that you have gone through the previous article on Process Synchronization.
We have discussed-
- Process Synchronization provides a synchronization among the processes.
- Synchronization mechanisms allow the processes to access critical section in a synchronized manner.
- This avoids the inconsistent results.
- Turn variable is a synchronization mechanism that provides synchronization among two processes.
- It uses a turn variable to provide the synchronization.
It is implemented as-
Initially, turn value is set to 0.
- Turn value = 0 means it is the turn of process P0 to enter the critical section.
- Turn value = 1 means it is the turn of process P1 to enter the critical section.
This synchronization mechanism works as explained in the following scenes-
- Process P0 arrives.
- It executes the turn!=0 instruction.
- Since turn value is set to 0, so it returns value 0 to the while loop.
- The while loop condition breaks.
- Process P0 enters the critical section and executes.
- Now, even if process P0 gets preempted in the middle, process P1 can not enter the critical section.
- Process P1 can not enter unless process P0 completes and sets the turn value to 1.
- Process P1 arrives.
- It executes the turn!=1 instruction.
- Since turn value is set to 0, so it returns value 1 to the while loop.
- The returned value 1 does not break the while loop condition.
- The process P1 is trapped inside an infinite while loop.
- The while loop keeps the process P1 busy until the turn value becomes 1 and its condition breaks.
- Process P0 comes out of the critical section and sets the turn value to 1.
- The while loop condition of process P1 breaks.
- Now, the process P1 waiting for the critical section enters the critical section and execute.
- Now, even if process P1 gets preempted in the middle, process P0 can not enter the critical section.
- Process P0 can not enter unless process P1 completes and sets the turn value to 0.
Also Read-Criteria For Synchronization Mechanisms
The characteristics of this synchronization mechanism are-
- It ensures mutual exclusion.
- It follows the strict alternation approach.
Strict Alternation Approach
In strict alternation approach,
- It does not guarantee progress since it follows strict alternation approach.
- It ensures bounded waiting since processes are executed turn wise one by one and each process is guaranteed to get a chance.
- It ensures processes does not starve for the CPU.
- It is architectural neutral since it does not require any support from the operating system.
- It is deadlock free.
- It is a busy waiting solution which keeps the CPU busy when the process is actually waiting.
To gain better understanding about Turn Variable,
Next Article-Interest Variable | Synchronization Mechanism
Get more notes and other study material of Operating System.
Watch video lectures by visiting our YouTube channel LearnVidFun.