Lets take two semaphores A = 0 & B = 1.
Then the process execution flow would look something like this,
Now in the above flowchart both processes are running concurrently. All the lines have the following meaning:
Line1 ) wait() is implemented on both A and B. But since A=0 therefore the process P1 will be stuck & the control will reach to process P2 until A is not released. Now value of B = 0.
Line2 ) Since P2 is running therefore it will use the resource R1. P1 is still stuck at Line1.
Line3 ) Now P2 releases A and hence P1 also starts to run right from Line1. Value of A = 0.
Line4 ) Both processes are running simultaneously but P2 gets stuck at wait(B) since B = 0 (Just like P1 got stuck at Line1). Till then P1 uses R1 & R2 and finally releases B. Value of B = 0 again.
Line5 ) P1 again gets stuck for A = 0 and P2 takes control and moves forward to use R2.
Line6 ) P2 is only running and using R3.
Line7 ) P2 releases A and hence P1 starts executing right from Line5. Value of A = 0 once again.
Line8 ) P1 finishes using R3 & R4 and P2 gets stuck at B since its value was 0. But at Line8 P1 releases B after which P2 moves ahead with execution. Value of B = 0.
Line9 ) P2 uses R4 and hence all resources get properly used by both the processes.
Line10 ) Since the value of B = 0, P2 ups the value of semaphore B to what it was before. Now value of A = 0, Value of B = 1.
Hence two semaphores got used.
Although I'm still trying to understand whether the use of exactly TWO semaphores would come to my mind intuitively in the exam or is it just a matter of practice.
Ref.https://www.geeksforgeeks.org/gate-gate-it-2005-question-42/