我有一个项目,我必须为信号量编写伪代码,从以下文本:
"考虑一个出租车将曼联和利物浦的支持者从市中心带到周六足球比赛的场景。出租车一次可以带四个支持者,并且在携带支持者时总是满载。然而,如果出租车包含一个独立的团队的支持者,则永远不会出现这种情况。出租车进行多次旅行,当它首次到达时,它会随机向两个等候的支持者队列中的一个发出信号。您可以假设在发出信号时,每个队列中始终有一个或多个支持者在等待。当一名支持者进入出租车并且在出租车中仍有一些空间供更多的支持者时,支持者(刚刚加入出租车)向其中一个排队等候的支持者发出信号,让他们也进入出租车。在可能的情况下,支持者将随机选择队列发出信号,但是如果有必要,他们将选择一个特定的队列,以确保在出租车中没有单独的支持者与对方的支持者隔离。
进入出租车的最后一名支持者在出租车中完成了四名支持者的完整队列,这标志着出租车(司机)将他们带到了足球场。出租车将他们带到目的地,然后返回重复循环。请注意,只有支持者(不是出租车司机)能够区分谁是曼联支持者和谁是利物浦支持者。"
我在应用我所拥有的笔记时遇到了问题,以及在线方式对此方案有何帮助。
到目前为止我做了什么:
int numManInTaxi = 0; //current no. of ManU supporters in taxi
int numLivInTaxi = 0;
sem MaxUnitedFans = 4; // // max no. of supporters that can fit in taxi
sem MaxLivFans = 4;
sem MMutexSem = 1;
sem LMutexSem = 1;
CO
for (count = 1 to ManUSupporter){
ManUProcess[count];
//
for (count = 1 to LivSupporter){
LivProcess[count];
OC
} /*end main process
process ManUProcess [i = 1 to N]{
P(MMutexSem); // mutually exclusice access for United supporter
numManUInTaxi++;
if ((numManInTaxi+numLivInTaxi) < 4)
{
if (numManuInTaxi == 3) { // signal the Man queue
numManUInTaxi++;
} else if ((numManUInTaxi ==1) && (numLivInTaxi==2)){
numManUInTaxi++;
} else if ( (numManInTaxi == 2) &&(numLivInTaxi==1)) {
V(MMutexSem);
NumLivInTaxi++;}
//end ManU supporter semaphore
答案 0 :(得分:0)
这是我能做的 -
int numManInTaxi = 0; //current no. of ManU supporters in taxi
int numLivInTaxi = 0;
int seats=4; //no of seats available empty
sem taxi=1; //to wait for taxi to send signal
sem seats=0; //signal generated by taxi or passenger for next passenger
wait(taxi); //taxi is available
{
signal(seat); //taxi generates signal
while(wait(seats)) //check if there are seats available
{
int i=rand()%2; //random number 0 or 1 used to select between 2 queues
if(i==0)
numManInTaxi++; //passenger supports ManU
else
numLivInTaxi++; //passenger supports Liv
seats--;
if(seats>1) //passenger generates signal for next passenger to enter
signal(seat);
}
/*Now three seats are filled and we have one empty seat left which is to
be filled such that there is no lone supporter of a team in taxi*/
signal(seat); //signal for last seat
wait(seat); //last passenger recieves the signal
seats--;
if(numManInTaxi==1) //if only one supporter belongs to ManU
numManInTaxi++;
else
numManInTaxi++;
}
//taxi drops passengers
numManInTaxi=0;
numManInTaxi=0;
seats=4;
signal(taxi); //taxi is ready for next trip