#include <iostream>
#include <bits/stdc++.h>
#include <chrono>
#include <mutex>
using namespace std;
class Scheduler{
private :
thread consumer_thread;
Scheduler( ) {
consumer_thread = thread( [ this ] ( ) { this- > consumeTasks( ) ; } ) ;
}
void consumeTasks( ) {
return ;
}
} ;
class Bathroom{
private :
int count = 0 ;
string state = "unset" ;
mutex m;
condition_variable cv;
public :
void MaleUseBathroom( string name) {
unique_lock< mutex> lock( m) ;
cv.wait ( lock, [ this ] { return ( state == "unset" ) || ( state == "male" && count < 2 ) ; } ) ;
//critical section
if ( state == "unset" ) {
state = "male" ;
}
count++ ;
lock.unlock ( ) ;
this_thread:: sleep_for ( 100ms) ; //using
cout << name<< " is using the bathroom" << endl;
lock.lock ( ) ;
count-- ;
if ( count == 0 ) {
state = "unset" ;
}
lock.unlock ( ) ;
cv.notify_all ( ) ;
}
void FemaleUseBathroom( string name) {
unique_lock< mutex> lock( m) ;
cv.wait ( lock, [ this ] { return ( state == "unset" ) || ( state == "female" && count < 2 ) ; } ) ;
//critical section
if ( state == "unset" ) {
state = "female" ;
}
count++ ;
lock.unlock ( ) ;
this_thread:: sleep_for ( 100ms) ; //using
cout << name<< " is using the bathroom" << endl;
lock.lock ( ) ;
count-- ;
if ( count == 0 ) {
state = "unset" ;
}
lock.unlock ( ) ;
cv.notify_all ( ) ;
}
} ;
void UseBathroom( Bathroom& bathroom, string name, int gender) {
if ( gender) {
bathroom.MaleUseBathroom ( name) ;
} else {
bathroom.FemaleUseBathroom ( name) ;
}
}
int main( ) {
// your code goes here
Bathroom b;
thread t1( UseBathroom, std:: ref ( b) , "atharva" , 1 ) ;
thread t2( UseBathroom, std:: ref ( b) , "vinda" , 0 ) ;
thread t3( UseBathroom, std:: ref ( b) , "athar" , 1 ) ;
thread t4( UseBathroom, std:: ref ( b) , "vind" , 0 ) ;
thread t5( UseBathroom, std:: ref ( b) , "ath" , 1 ) ;
thread t6( UseBathroom, std:: ref ( b) , "vin" , 0 ) ;
thread t7( UseBathroom, std:: ref ( b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