Code:
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <bits/stdc++.h>
#include <atomic>
using namespace std;
mutex mtx; // mutex 1 means free, 0 means occupied
condition_variable barber_cv, customer_cv;
int waitingCustomers = 0; // waitingCustomers count
void barber()
{
while (true)
{
unique_lock<mutex> lock(mtx); // locking
cout << "Barber is sleeping..." << endl;
customer_cv.wait(lock, [] { return waitingCustomers > 0; });
cout << "Barber is cutting hair." << endl;
lock.unlock(); // unlocking
barber_cv.notify_one();
this_thread::sleep_for(chrono::seconds(1));
}
}
void customer(int id)
{
unique_lock<mutex> lock(mtx);
if (waitingCustomers < 3)
{
cout << "Customer " << id << " enters the barber shop." << endl;
waitingCustomers++;
customer_cv.notify_one();
barber_cv.wait(lock);
cout << "Customer " << id << " is getting a haircut." << endl;
waitingCustomers--;
cout << "Customer " << id << " leaves the barber shop." << endl;
}
else
cout << "Customer " << id << " leaves because the barber shop is
full." << endl;
customer_cv.notify_one();
}
int main()
{
thread barberThread(barber);
barberThread.detach();
vector<thread> customerThreads;
for (int i = 1; i <= 10; i++)
{
int id = i;
customerThreads.emplace_back(customer, id);
this_thread::sleep_for(chrono::milliseconds(500));
}
for (auto &thread : customerThreads) thread.join();
return 0;
}
OUTPUT:
Barber is sleeping... Customer 4 leaves the barber shop.
Customer 1 enters the barber shop. Customer 7 enters the barber shop.
Barber is cutting hair. Customer 8 leaves because the barber
Customer 1 is getting a haircut. shop is full.
Customer 1 leaves the barber shop. Barber is sleeping...
Customer 2 enters the barber shop. Barber is cutting hair.
Barber is sleeping... Customer 5 is getting a haircut.
Barber is cutting hair. Customer 5 leaves the barber shop.
Customer 2 is getting a haircut. Customer 9 enters the barber shop.
Customer 2 leaves the barber shop. Customer 10 leaves because the
Customer 3 enters the barber shop. barber shop is full.
Customer 4 enters the barber shop. Barber is sleeping...
Barber is sleeping... Barber is cutting hair.
Barber is cutting hair. Customer 6 is getting a haircut.
Customer 3 is getting a haircut. Customer 6 leaves the barber shop.
Customer 3 leaves the barber shop. Barber is sleeping...
Customer 5 enters the barber shop. Barber is cutting hair.
Customer 6 enters the barber shop. Customer 7 is getting a haircut.
Barber is sleeping... Customer 7 leaves the barber shop.
Barber is cutting hair. Barber is sleeping...
Customer 4 is getting a haircut. Barber is cutting hair.
Customer 9 is getting a haircut.
Customer 9 leaves the barber shop.