我正在寫一個模擬一個男女皆宜的浴室的程序(用於作業)。一次只允許4人入住,如果另一個人已經在使用浴室,男人和女人不能入住。我的問題是允許最多4人在浴室。從輸出中可以看到,一次只有1人進入洗手間。這裏是我的代碼:相互排斥和信號量
const int Delayx = 60;
int i;
int restroom = 0;
int Menwaiting = 0;
int Womenwaiting = 0;
semaphore max_capacity;
semaphore woman;
semaphore man;
semaphore mutex;
semaphore restroomcount;
void Delay(void)
{
int DelayTime;
DelayTime = random(Delayx);
for (i = 0; i<DelayTime; i++);
}
void Woman(void)
{
// for(;;){
Womenwaiting++;
//wait(mutex);
wait(woman);
wait(max_capacity);
//wait(woman);
wait(mutex);
wait(restroomcount);
cout << "A Woman has entered Restroom"<<endl;
cout << "People in the Restroom:" << restroom++ <<endl <<endl;
signal(restroomcount);
Womenwaiting--;
Delay();
wait(restroomcount);
cout << "A woman has exited Restroom"<<endl;
cout << "People in the Restroom:" << restroom-- <<endl<<endl;
signal(restroomcount);
signal(mutex);
signal(max_capacity);
if(Menwaiting > Womenwaiting){
signal(man);
}
else{
signal(woman);
}
//signal(max_capacity);
//signal(man);
// }
}
void Man(void)
{
// for(;;){
Menwaiting++;
//wait(mutex);
wait(man);
wait(max_capacity);
//wait(man);
wait(mutex);
wait(restroomcount);
cout <<"A Man has entered the Restroom"<<endl;
cout <<"People in the Restroom:" << restroom++ <<endl<<endl;
signal(restroomcount);
Menwaiting--;
//signal(mutex);
Delay();
//wait(mutex);
wait(restroomcount);
cout << "A man has exited the Restroom"<<endl;
cout <<"People in the Restroom:" << restroom-- <<endl<<endl;
signal(restroomcount);
signal(mutex);
signal(max_capacity);
if(Womenwaiting > Menwaiting){
signal(woman);
}
else{
signal(man);
}
//signal(max_capacity);
//signal(woman);
//}
}
void main()
{
initialsem(woman,1);
initialsem(man,1);
initialsem(max_capacity,4);
initialsem(mutex,1);
initialsem(restroomcount,1);
cobegin
{
Woman(); Woman(); Woman(); Woman(); Woman(); Man(); Man(); Man(); Man(); Man();
}
}
這將生成以下的輸出:
一名男子進入洗手間
人們在廁所:1的人已經退出了廁所
洗手間裏的人:0一個男人已經進入洗手間
人們在廁所:1的人已經退出了廁所
人們在廁所:0一個女人進入廁所
人們在廁所:1一個女人已退出廁所
人們在廁所:0一個女人進入廁所 在洗手間
人:1一個女人已經離開廁所
人們在廁所:0
依此類推,直到永遠。
這段代碼的一部分,被認爲是負責預防男人進入洗手間,如果那裏已經有女人了,反之亦然? – 2010-10-03 16:03:43
這個任務應該是單線程的嗎?使用線程?協同程序? – dgnorton 2010-10-03 16:17:35
我不明白:如果男女不能同時進入同一個房間,他們應該怎麼做愛? – ereOn 2010-10-03 16:20:09