Crossing the single-plank bridge problem

 1. Conditions: Only one direction of vehicles can pass at a time, and all vehicles on this side can pass through (this process can have vehicles continuing to pass in this direction), and then the other side can open to traffic.

2. Several semaphores are required: one-way traffic semaphore (2)

                                Allow K cars to pass the car semaphore

                                Mutual exclusive access count semaphore

                                Count: Count the number of cars on the bridge (easy to miss)

semaphore wait,mutex1,mutex2;
mutex1=mutex2=1;
bridge=k;wait1;
int counter1=counter2=0;

cobegin east{
P(mutex1);
counter1++;
if(counter1==1)P(wait);//只需要在第一车来时判断,因为已经触发了P(wait)
V(mutex1);
P(bridge);
/*过桥*/
V(bridge);
P(mutex1);
counter1--;
if(counter1==0) V(wait);
V(mutex1);
}
coend

cobegin west{
P(mutex2);
counter2++;
if(counter2==1)P(wait);
V(mutex2);
P(bridge);
/*过桥*/
V(bridge);
P(mutex2);
counter2--;
if(counter2==0) V(wait);
V(mutex2);
}
coend

See the previous operating system for details on PV operations

Guess you like

Origin blog.csdn.net/qq_52913088/article/details/120716818