Use semaphores to solve the "over-the-bridge" problem: pedestrians in the same direction can cross a row, and pedestrians in the other direction have to wait when someone is crossing the bridge in one direction; pedestrians in the other direction can cross the bridge when no one is in one Direction
The two directions of the single-plank bridge are marked as a and B respectively, and the CountA and COUNTB of the shape variables represent the number of pedestrians on the single-plank bridge in the direction of A and b respectively, and the initial value is 0; then set three mutually exclusive semaphores of the initial value 1: SA is used to implement mutually exclusive access to CountA. SB is used to achieve mutually exclusive access to the COUNTB, and the mutex is used to realize the mutual exclusion of the pedestrian from the two directions. is described as follows:
The two directions of the single-plank bridge are marked as a and B respectively, and the CountA and COUNTB of the shape variables represent the number of pedestrians on the single-plank bridge in the direction of A and b respectively, and the initial value is 0; then set three mutually exclusive semaphores of the initial value 1: SA is used to implement mutually exclusive access to CountA. SB is used to achieve mutually exclusive access to the COUNTB, and the mutex is used to realize the mutual exclusion of the pedestrian from the two directions. The following is described in detail
Var sa,sb,mutex:semaphore:=1,1,1;
Counta,countb:integer:=0,0:begin Parbegin Process A:begin
Wait (SA);
if (counta=0) then wait (mutex): counta:=counta+1;
Signal (SA);
Cross-bridge; wait (SA);
Counta:=counta-1;
if (counta=0) then signal (mutex);
Signal (SA);
End Process B:begin Wait (SB);
if (countb=0) then wait (mutex);
countb:=countb+1;
Signal (SB);
Cross-bridge;
Wait (SB);
Countb:=countb-1;
if (countb=0) then signal (mutex);
Signal (SB); End Parend
End