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

502 阅读1分钟

独木桥问题变式一


一、问题描述

东西方向汽车过独木桥,为保证安全,只要桥上无车,则允许一方的汽车过桥,待另一方的车全部过完后,另一方的车才允许过桥,桥面上最多可以有K辆汽车通过


二、问题求解

🔑:

int eastCount=0;        //当前从东边上桥的汽车数量
int westCount=0;        //当前从西边上桥的汽车数量
semaphore bridge=1;     //两边的车互斥申请桥
semaphore eastMutex=1;  //互斥访问eastCount
semaphore westMutex=1;  //互斥访问westCount
semaphore maxNum=k;     //桥上最大汽车数量

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

        P(maxNum);
        从东边过桥;
        V(maxNum);

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

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

        P(maxNum);
        从西边过桥;
        V(maxNum);

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

三、碎碎念

过桥的时候申请一个maxNum资源即可。