浴室同步和线程队列

时间:2012-05-06 21:44:42

标签: c++ semaphore

对于家庭作业,我们已经获得了浴室同步问题。我一直在努力想弄清楚如何开始。当一个人进入洗手间时,我想做什么(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);
         }
     }

}

1 个答案:

答案 0 :(得分:1)

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

你需要:
互斥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);