2017-03-01 17 views
0

我有一個項目,我必須寫僞信號量,從下面的文字:併發編程,我該如何構造一個信號量?

「考慮在一個單一的出租車正在曼聯和利物浦的支持者從市中心到週六足球比賽的場景。出租車一次可帶四名支持者,攜帶支持者時總是滿員,但在出租車中只有一名支持者獨立分開時,情況絕不允許出現,出租車進行多次出行當它第一次到達時,它隨機發出信號給兩個等待支持者隊列中的一個隊列,你可以假設每個隊列中有一個或多個支持者在發信號時等待,當一個支持者進入出租車時,還有一些房間爲更多的支持者在出租車上的支持者(誰剛剛加入出租車)發信號給另一個等待的支持者在隊列中,他們也進入出租車。在可能的情況下,支持者將隨機選擇要發信號的隊列,但如果有必要,他們會選擇一個特定的隊列,以確保沒有單個支持者在與相反支持者的出租車中隔離。

最後一名進入出租車的支持者在出租車上完成了一個由四名支持者組成的隊伍的信號,告訴出租車司機將他們帶到足球場。出租車將他們帶到目的地,然後返回重複循環。請注意,只有支持者(不是出租車司機)能夠區分誰是曼聯的支持者,誰是利物浦的支持者。「

我在申請筆記時遇到了麻煩,網上這種情況下

繼承人什麼香港專業教育學院迄今所做的:?

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 
+1

你嘗試過什麼你會得到更多更好的答案如果你展示你的嘗試,並證明你已花時間去嘗試幫助自己。請參閱[問] –

+0

我試圖構建它,但我幾乎肯定它不正確。 在這種情況下,它可以是來自聯合起來的一名出租車的人的4個支持,來自每組支持者的2個支持者,或者4個利物浦支持者。 不應該有一個場景,其中一組支持者超過另一組。 – 944jmc

+0

對不起,對此新增功能,現在添加到主要問題 – 944jmc

回答

0

這是我能make-

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 
相關問題