信号量和并发编程

Jen*_*Jen 7 c concurrency semaphore

对于家庭作业,我需要编写以下场景.这将使用BACI(即C--)使用信号量来完成

有2个男女皆宜的洗手间,每个可容纳4人.由于它是男女皆宜的,只有同性的人可以同时在洗手间,而FIFO并不重要.我脑子里有一个基本的"算法"来处理4个男人和4个女人的1个厕所.但我不知道如何编码.任何帮助将不胜感激.这就是我所拥有的.

Woman:

Check to see if there are any men in the restroom. If so "wait".
If no men check to see if there are 4 people. If so "wait".
If no men and not 4 use restroom. When leaving signal there is a vacancy.
If last woman signal the men if they are waiting if not signal the woman.


Man:

check to see if there are any woman in the restroom. if so "wait"
If no woman check to see if there are 4 people. If so "wait".
If no woman and not 4 use restroom. when leaving signal there is a vacancy.
if last man signal the women if they are waiting if not signal the men.
Run Code Online (Sandbox Code Playgroud)

提供了这些附加说明

  • 使用随机FOR循环来模拟适当位置的时间流逝.这可以通过使用延迟功能轻松完成:

    void Delay (void)
    { 
      int i;
      int DelayTime;
      DelayTime = random (DELAY);
      for (i = 0; i < DelayTime; i++):
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 其中const int DELAY = 10到100之间的某个数字.

  • 很好地打印和格式化输出并以这样的方式打印消息:通过读取输出,可以跟踪执行顺序.
  • 将进程设置为永久循环,并使用控件C(或控制中断)来停止程序.

Jen*_*Jen 0

这是我所拥有的。这使得一次可以有 1 个人在卫生间里,而不会出现僵局或饥饿。我需要帮助来了解如何让 4 个人同时使用洗手间。

const int Delayx = 60;
int i;
semaphore max_capacity;
semaphore woman;
semaphore man;
semaphore mutex;

void Delay(void)
{
    int DelayTime;
    DelayTime = random(Delayx);
    for (i = 0; i<DelayTime; i++);
}

void Woman(void)
{
    wait(woman);
    wait(max_capacity);
    wait(mutex);
    cout << "A Woman has entered Restroom"<<endl;
    Delay();
    cout << "A woman has exited Restroom"<<endl;
    signal(mutex);
    signal(max_capacity);
    signal(man);
}

void Man(void)
{
    wait(man);
    wait(max_capacity);
    wait(mutex);
    cout <<"A Man has entered the Restroom"<<endl;
    Delay();
    cout << "A man has exited the Restroom"<<endl;
    signal(mutex);
    signal(max_capacity);
    signal(woman);
}

void main()
{
    initialsem(woman,1);
    initialsem(man,1);
    initialsem(max_capacity,4);
    initialsem(mutex,1);
    cobegin
    {
        Woman(); Woman(); Woman(); Woman(); Woman(); Woman(); Woman(); Woman(); Man();  Man(); Man(); Man(); Man(); Man(); Man(); Man();
    }
}
Run Code Online (Sandbox Code Playgroud)