gpt4 book ai didi

c++ - 互斥和信号量

转载 作者:可可西里 更新时间:2023-11-01 15:25:01 29 4
gpt4 key购买 nike

我正在编写一个模拟男女通用浴室的程序(用于家庭作业)。一次只允许 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();
}

}

这会生成以下输出:

A Man has entered the Restroom
People in the Restroom:1

A man has exited the Restroom
People in the Restroom:0

A Man has entered the Restroom
People in the Restroom:1

A man has exited the Restroom
People in the Restroom:0

A Woman has entered Restroom
People in the Restroom:1

A woman has exited Restroom
People in the Restroom:0

A Woman has entered Restroom
People in the Restroom:1

A woman has exited Restroom
People in the Restroom:0

以此类推,直到永远。

最佳答案

我认为你的信号量太多了。你的男人/女人信号灯一次只针对 1 个人。考虑使用一些受互斥锁保护的状态变量(浴室的当前性别、浴室中的人数)而不是这么多不同的信号量。

您是否保持排队顺序,或者人们是否可以根据当前洗手间性别跳过?例如,如果你有 woman,woman,woman,man,woman,第 4 个女人是否允许跳过男人进入洗手间,或者让 3 个女人退出,然后男人进入/退出,然后女人可以进入?这是一个比允许跳过更容易的问题。

关于c++ - 互斥和信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3850491/

29 4 0