For homework we have been given the bathroom synchronization problem. I have been struggling trying to figure out how to start. What I would like to do when a person enter the restroom(personEnterRestrrom function), if they are female and no males are in the restroom they enter,if not they go into a queue for women waiting. I want to do the same for men. I tried to implement a queue that holds thread, but cannot get it to work. Then in personLeavesRestroom function. When a person leaves if no one is left in the bathroom the other queue starts. Here is my code, I know I am far off, by I do need some guidance and am not very familiar with semaphores.
//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);
}
}
}