Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- import time
- import random
- barber_wakeup = 1
- customer_semaphore = threading.Semaphore(0)
- barber_semaphore = threading.Semaphore(0)
- mutex = threading.Semaphore(1)
- class Barber:
- def cut_hair(self, customer):
- for _ in range(3):
- print("\nBarber is cutting hair of {0}".format(customer))
- time.sleep(2)
- print("\n{0} is done and leaving barber shop".format(customer))
- class Customer:
- def __init__(self, name):
- self.name = name
- def get_hair_cut(self, customer):
- for _ in range(3):
- print("\nCustomer {0} is having haircut".format(customer))
- time.sleep(2)
- def leave(self, customer):
- print("\nWaiting room if full, customer {0} is leaving".format(customer))
- class BarberShop:
- waiting_cust = []
- def __init__(self, barber, total_chairs):
- self.barber = barber
- self.total_chairs = total_chairs
- print("Total seats: {0}".format(total_chairs))
- def barber_thread(self):
- bt = threading.Thread(target=self.barber_working)
- bt.start()
- def entry(self, customer):
- print("\nCustomer {0} has entered".format(customer))
- mutex.acquire()
- if len(self.waiting_cust) < self.total_chairs:
- print("\nCustomer {0} founds an empty seat".format(customer))
- self.waiting_cust.append(customer)
- global barber_wakeup
- while barber_wakeup:
- customer_semaphore.release()
- print("\nCustomer {0} wakes up the barber".format(customer))
- barber_wakeup = 0
- print("\nCustomer {0} sits on a waiting chair".format(customer))
- mutex.release()
- print("\nCustomer {0} is waiting to be called by barber".format(customer))
- barber_semaphore.acquire()
- Customer.get_hair_cut(self, customer)
- else:
- mutex.release()
- Customer.leave(customer)
- def barber_working(self):
- while True:
- if len(self.waiting_cust) == 0:
- global barber_wakeup
- print("Barber is sleeping")
- barber_wakeup = 1
- customer_semaphore.acquire()
- if len(self.waiting_cust) > 0:
- mutex.acquire()
- cust = self.waiting_cust[0]
- print("\nBarber calls {0}".format(cust))
- del self.waiting_cust[0]
- barber_semaphore.release()
- mutex.release()
- self.barber.cut_hair(cust)
- customer_list = []
- barber = Barber()
- barber_shop = BarberShop(barber, 3)
- barber_shop.barber_thread()
- customer_list.append(Customer("Кирилл"))
- customer_list.append(Customer("Артем"))
- customer_list.append(Customer("Артур"))
- customer_list.append(Customer("Данила"))
- customer_list.append(Customer("Владислав"))
- customer_list.append(Customer("VanDarkholm"))
- customer_list.append(Customer("Vasya"))
- while len(customer_list) != 0:
- c = customer_list.pop()
- t = threading.Thread(target = barber_shop.entry, args=(c.name,))
- time.sleep(random.randint(1, 5))
- t.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement