当前位置:网站首页>PV operation daily question 1 - single wooden bridge problem (variant 2)

PV operation daily question 1 - single wooden bridge problem (variant 2)

2022-06-10 16:11:00 liangsena


One 、 Problem description

The car passes the single wooden bridge in the east-west direction , To ensure safety , As long as there is no car on the bridge , Then one side's car is allowed to cross the bridge , When all the cars of the other side have passed , The other side's car is allowed to cross the bridge . And the vehicles in all directions are required to cross the bridge in series , But when the other side offered to cross the bridge , It shall be able to prevent the other party's successor vehicles that have not been on the bridge , After the vehicles on the bridge deck pass , The car on the other side began to cross the bridge .


Two 、 problem solving

int eastCount=0;        // The current number of cars on the bridge from the East 
int westCount=0;        // The current number of cars on the bridge from the West 
semaphore bridge=1;     // The cars on both sides are mutually exclusive 
semaphore eastMutex=1;  // Exclusive access eastCount
semaphore westMutex=1;  // Exclusive access westCount
semaphore pass=1;       // It is used to block the other party's subsequent vehicles from getting on the bridge 

East()
{
    
    while(1)
    {
    
        P(pass)
        P(eastMutex);
        if(eastCount==0)
        {
    
            P(bridge);
        }
        eastCount++;
        V(eastMutex);
        V(pass);

        P(maxNum);
         Cross the bridge from the East ;
        V(maxNum);

        P(eastMutex);
        eastCount--;
        if(eastCount==0)
        {
    
            P(bridge);
        }
        V(eastMutex);
    }
}

West()
{
    
    while(1)
    {
    
        P(pass);
        P(westMutex);
        if(westCount==0)
        {
    
            P(bridge);
        }
        westCount++;
        V(eastMutex);
        V(pass);

        P(maxNum);
         Cross the bridge from the West ;
        V(maxNum);

        P(westMutex);
        westCount--;
        if(westCount==0)
        {
    
            P(bridge);
        }
        V(westMutex);
    }
}


3、 ... and 、 twitter

pass Semaphore , When one party wants to cross the bridge, apply first , If you can't apply, it means that you have been blocked by the other party . Also apply to pass, Then block the other party's progress .

原网站

版权声明
本文为[liangsena]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101014232617.html