First of all, the above code is a standard PETERSON'S SOLUTION FOR SYNCHRONIZATION OF TWO PROCESSES.
Now lets move to your question: How is bounded waiting satisfied here?
BOUNDED WAITING: After a limited number of attempts, the interested process must be allowed to enter the critical section.
Flow of above code:
- Process 'i' declares itself as interested to enter the CS by marking its flag=true.
- Now, while 'i' is interested, it checks whether the turn is given to 'j'?
- If it is process j turn now, then it marks itself as not interested to enter CS by setting flag=false.
- Process 'i' keeps on checking if process j turn has ended or not in the next while loop (while(turn==j);)
- Process i will break out of while loop only when process j makes turn = i.
- After this, the process i will mark itself interested by setting flag=true.
- Then , it will enter CS, and again will give turn to process j by setting turn=j just before leaving CS.
In this way, the two processes will keep alternating.
The main thing to note here is that, a process a will have finite statements in its CS to execute, that eventually means that the statement "turn=j" will be executed by each process surely.
I know why you got this doubt.The statement turn=j made you think that everytime, the turn is given to process j. But the question mentions that, if current process is Pi then the other process is Pj where j=1-i.
So if i=0,then j=1 and if i=1, then j=0...
I recommend you to watch this:https://youtu.be/XAsAAJSotA4
Happy Learning