浴室同步和线程队列

2023-12-13

对于家庭作业,我们被要求解决浴室同步问题。我一直在努力思考如何开始。当一个人进入洗手间(personEnterRestrrom 函数)时我想要做什么,如果他们是女性并且没有男性在他们进入的洗手间里,如果不是,他们会进入等待女性的队列。我想为男人做同样的事情。我试图实现一个保存线程的队列,但无法让它工作。然后在personLeavesRestroom函数中。当一个人离开时,如果浴室里没有人,另一个队列就会开始。这是我的代码,我知道我还很遥远,因为我确实需要一些指导并且对信号量不是很熟悉。

//declarations
pthread_mutex_t coutMutex;
int menInBath;
int womanInBath;
int menWaiting;
int womenWaiting;
queue<pthread_mutex_t>men;
queue<pthread_mutex_t>women;


 personEnterRestroom(int id, bool isFemale)
 {
   // LEAVE THESE STATEMENTS                                                 
   pthread_mutex_lock(&coutMutex);
  cout << "Enter: " << id << (isFemale ? " (female)" : " (male)") << endl;
  pthread_mutex_unlock(&coutMutex);

  // TODO: Complete this function                                           
 if(isFemale && menInBath<=0)
  {
     womanInBath++;
   }
 else if(isFemale && menInBath>0)
 {
  wait(coutMutex);
  women.push(coutMutex);
}
 else if(!isFemale && womanInBath<=0)
{
  menInBath++;
}
else
{
  wait(coutMutex);
  men.push(coutMutex);
}

}

   void
    personLeaveRestroom(int id, bool isFemale)  
    {
   // LEAVE THESE STATEMENTS                                                 
    pthread_mutex_lock(&coutMutex);
    cout << "Leave: " << id << (isFemale ? " (female)" : " (male)") << endl;
    pthread_mutex_unlock(&coutMutex);

  if(isFemale)
    womanInBath--;
  if(womanInBath==0)
    {
       while(!men.empty())
         {
           coutMutex=men.front();
           men.pop();
           signal(coutMutex);
         }
     }

}

如果您正在寻找 FIFO 互斥体,这个可以帮助您:

你需要:
mutex (pthread_mutex_t mutex),
条件变量数组 (std::vector<pthread_cond_t> cond)
and 存储线程ID的队列 (std::queue<int> fifo).

假设有N带 ID 的线程0 to N-1. Then fifo_lock() and fifo_unlock()可能看起来像这样(伪代码):

fifo_lock()
    tid = ID of this thread;
    mutex_lock(mutex);
    fifo.push(tid); // puts this thread at the end of queue

    // make sure that first thread in queue owns the mutex:
    while (fifo.front() != tid)
        cond_wait(cond[tid], mutex);

    mutex_unlock(mutex);

fifo_unlock()
    mutex_lock(mutex);
    fifo.pop(); // removes this thread from queue

    // "wake up" first thread in queue:
    if (!fifo.empty())
        cond_signal(cond[fifo.front()]);

    mutex_unlock(mutex);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

浴室同步和线程队列 的相关文章

随机推荐