-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSleeping Barber's Problem.py
More file actions
63 lines (54 loc) · 2.06 KB
/
Sleeping Barber's Problem.py
File metadata and controls
63 lines (54 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import threading
import time
import random
# Define the maximum number of customers and the number of chairs in the waiting room
max_customers = int(input("Enter max no. of customers: "))
num_chairs = int(input("Enter max no. of chairs: "))
# Define the semaphores for the barber, the customers and the mutex
barber_semaphore = threading.Semaphore(0)
customer_semaphore = threading.Semaphore(0)
mutex = threading.Semaphore(1)
# Define a list to keep track of the waiting customers
waiting_customers = []
# Define the barber thread function
def barber():
while(True):
print("The barber is sleeping......")
barber_semaphore.acquire()
mutex.acquire()
if len(waiting_customers) > 0:
customer = waiting_customers.pop(0)
print(f"The barber is cutting hair for customer {customer}.")
mutex.release()
time.sleep(random.randint(1, 5))
print(f"The barber has finished cutting hair for customer {customer}.")
customer_semaphore.release()
else:
mutex.release()
# Define the customer thread function
def customer(index):
while(True):
global waiting_customers
time.sleep(random.randint(1, 5))
mutex.acquire()
if len(waiting_customers) < num_chairs:
waiting_customers.append(index)
print(f"Customer {index} is waiting in the waiting room.")
mutex.release()
barber_semaphore.release()
customer_semaphore.acquire()
print(f"Customer {index} has finished getting the haircut.")
else:
print(f"Customer {index} is leaving, because the waiting room is full.")
mutex.release()
# Create a thread for the barber
barber_thread = threading.Thread(target=barber)
# Create a thread for each customer
customer_threads = []
for i in range(max_customers):
customer_threads.append(threading.Thread(target=customer, args=(i, )))
# Start the barber and customer threads
barber_thread.start()
for thread in customer_threads:
thread.start()
# Wait for the customer