1

宿題として、バスルームの同期問題が与えられました。どのように始めたらよいのか、ずっと悩んでいました。人がトイレに入ったときにやりたいこと(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);
         }
     }

}
4

1 に答える 1

1

FIFOミューテックスを探しているなら、これが役に立ちます:

必要になるのは、
mutex ( pthread_mutex_t mutex)、
条件変数の配列( std::vector<pthread_cond_t> cond)
、およびスレッド ID を格納するためのキュー( std::queue<int> fifo) です。

Nに ID0を持つスレッドがあるとしN-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);
于 2012-05-06T22:34:17.863 に答える