PV操作每日一题-独木桥问题(变式二)

327 阅读1分钟

独木桥问题变式二


一、问题描述

东西方向汽车过独木桥,为保证安全,只要桥上无车,则允许一方的汽车过桥,待另一方的车全部过完后,另一方的车才允许过桥。且要求各方向的汽车串行过桥,但当另一方提出过桥时,应能阻止对方未上桥的后继车辆,待桥面的车过完后,另一方的汽车开始过桥。


二、问题求解

🔑:

int eastCount=0;        //当前从东边上桥的汽车数量
int westCount=0;        //当前从西边上桥的汽车数量
semaphore bridge=1;     //两边的车互斥申请桥
semaphore eastMutex=1;  //互斥访问eastCount
semaphore westMutex=1;  //互斥访问westCount
semaphore pass=1;       //用于阻断对方后续车辆上桥

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

        P(maxNum);
        从东边过桥;
        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);
        从西边过桥;
        V(maxNum);

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

三、碎碎念

pass信号量,在一方想过桥时先申请,申请不到就说明被对方阻断了。同样申请到pass,则阻断对方的进程。