浴室同步和线程队列

2022-05-11 00:00:00 semaphore c++

对于家庭作业,我们遇到了卫生间同步的问题。我一直在努力想办法从哪里开始。我想做什么,当一个人进入洗手间(PersonEnterRestrrom函数),如果他们是女性,并且没有男性在洗手间,他们进入,如果不是,他们进入排队等待女性。我也想为男人做同样的事情。我试图实现一个包含线程的队列,但无法使其工作。然后在PersLeavesRestRoom函数中。当一个人离开时,如果浴室里没有人,另一个人就会开始排队。这是我的代码,我知道我离得很远,我确实需要一些指导,并且不太熟悉信号量。

//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);
         }
     }

}

解决方案

如果您正在寻找先进先出互斥锁,此互斥锁可能会对您有所帮助:

您需要:
互斥体(pthread_mutex_t mutex),
条件变量数组(std::vector<pthread_cond_t> cond)
和线程ID存储队列(std::queue<int> fifo)。

假设有N个ID为0N-1的线程。则fifo_lock()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);

相关文章