Implemented with double rendezvous

This commit is contained in:
Romain CLEMENT 2023-10-16 20:43:14 +02:00
parent 12fe9a21d5
commit e187751e5a

View File

@ -12,60 +12,69 @@ mutex cout_mutex;
#define N 25 #define N 25
// GLOBAL VARIABLES // GLOBAL VARIABLES
counting_semaphore free_chairs(N); int customers = 0;
binary_semaphore barber_free(1); mutex mutexCustomer;
binary_semaphore barber_sem(1); counting_semaphore customer(0);
counting_semaphore barber(0);
void get_haircut(size_t id) counting_semaphore customerDone(0);
{ counting_semaphore barberDone(0);
this_thread::sleep_for(chrono::seconds(10));
print("Client " << id << " got a haircut");
}
void cutHair()
{
this_thread::sleep_for(chrono::seconds(10));
print("Barber cut hair");
}
void client(size_t id) void client(size_t id)
{ {
print("Client " << id << " arrived"); // customer enters
bool isAChairFree = free_chairs.try_acquire(); print("Customer " << id << " enters the barbershop");
if (!isAChairFree){ mutexCustomer.lock();
print("no chairs available"); if (customers == N) {
print("Client " << id << " left"); mutexCustomer.unlock();
return; //Bye bye print("Customer " << id << " bulks");
return;
} }
++customers;
mutexCustomer.unlock();
//wait for barber // rendezvous 1
barber_free.acquire(); customer.release(); // signal X
print("Client " << id << " woke the barber up"); barber.acquire(); // wait Y
barber_sem.release();
// Get a haircut // getHairCut
get_haircut(id); print("Customer " << id << " get his hair cut");
// Bye bye; this_thread::sleep_for(chrono::seconds(1));
free_chairs.release(); print("Customer " << id << " got a haircut");
print("Client " << id << " left");
// rendezvous 2
customerDone.release(); // signal X'
barberDone.acquire(); // wait Y'
// customer leaves
mutexCustomer.lock();
--customers;
mutexCustomer.unlock();
print("Customer " << id << " leaves the barbershop");
} }
void barber() void barber()
{ {
while (true) { while (true) {
print("Barber is sleeping"); // rendezvous 1
barber_sem.acquire(); customer.acquire(); // wait X
print("Barber woke up"); barber.release(); // signal Y
cutHair();
barber_free.release(); // cutHair
print("Barber starts to cut hair");
this_thread::sleep_for(chrono::seconds(1));
print("Barber stops to cut hair");
// rendezvous 2
customerDone.acquire(); // wait X'
barberDone.release(); // signal Y'
} }
} }
int main() int main()
{ {
barber_sem.acquire(); print("Barbershop opening with " << N << " chairs");
thread barber_thread(barber); thread barberThread(barberProcedure);
print("Client will arrive");
vector<thread> clients {}; vector<thread> clients {};
for(size_t i = 0; i < N+1; ++i) for(size_t i = 0; i < N+1; ++i)
{ {