可能重複:
bathroom synchronization and queue of threads麻煩figuing出邏輯浴室同步化
我已經看過堆棧類似的問題,並使用谷歌,他們沒有幫我回答我的問題。對於作業,我得到了浴室同步問題。共用浴室,女性不能使用,而男性在那裏,反之亦然。我想弄清楚的是,如果另一個性愛在浴室裏,如何停止並重新啓動線程。到目前爲止,我有幾個條件,如果沒有一個異性在那裏去,如果沒有,我告訴信號量等待。然後當離開時,如果沒有你的性別留在洗手間,讓其他性別(信號量去)。我不知道如果我在鎖定線程或讓信號量等待時遇到問題。這是我的代碼。
//我的變量
sem_t male;
sem_t female;
int maleInBath;
int femaleInBath;
pthread_mutex_t coutMutex;
//初始化變量
void personInitGlobals()
{
// LEAVE THIS STATEMENT
pthread_mutex_init(&coutMutex, NULL);
// TODO: Complete this function
int init=0;
maleInBath=0;
femaleInBath=0;
sem_init(&male, 0, init);
sem_init(&female, 0, init);
}
//進入洗手間
void 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 && maleInBath==0){
femaleInBath++;
}else if(isFemale && maleInBath >0){
sem_wait(&female);
}else if(!isFemale && femaleInBath==0){
maleInBath++;
}else{
sem_wait(&male);
}
}
人離開洗手間
void personLeaveRestroom(int id, bool isFemale)
{
// LEAVE THESE STATEMENTS
pthread_mutex_lock(&coutMutex);
cout << "Leave: " << id << (isFemale ? " (female)" : " (male)") << endl;
pthread_mutex_unlock(&coutMutex);
// TODO: Complete this function
if(isFemale){
femaleInBath--;
if(femaleInBath==0){
sem_post(&male);
}
}else{
maleInBath--;
if(maleInBath==0){
sem_post(&female);
}
}
}
嗯,其他人在幾天前發佈了關於此同一作業的問題。 –
@SamDufel:http://stackoverflow.com/questions/3850491/mutual-exclusion-and-semaphores(oops 2010!) – Flexo