操作系统练习 - 窄桥过车

版权声明:欢迎交流讨论 https://blog.csdn.net/qq_37746973/article/details/82959619

有一窄桥每次只能过一辆车,每次为了保证正常通行,只要桥上没有车,就允许一端的车过桥,待其全部过完后才允许另一端的车过桥。请用信号量和PV操作写出过窄桥的同步算法。

 

解:

  设2个变量, 3个信号量。

left 代表左边车的数量

right代表右边车的数量

leftPass  代表行驶方向为左车通行  

RightPass  代表行驶方向为右车通行

mutex 代表是否有车在桥上   

 

int left = n,  right = m;

Semaphore  mutex = 1,  leftPass = 1,  rightPass = 0;

//左车通行

void letfGo () {
    wait( mutex );
    wait( leftPass ) ;
    if ( left > 0 ) {
        左车通行
        left = left - 1;
    } else {
        single( rightPass )
    }
    single ( mutex );
}
 //右车通行

void rightGo () {
    wait( mutex );
    wait( rightPass ) ;
    if (right > 0 ) {
        左车通行
        right = right - 1;
    } else {
        single( leftPass )
    }
    single ( mutex );
}

猜你喜欢

转载自blog.csdn.net/qq_37746973/article/details/82959619
今日推荐