Last active
October 19, 2021 07:49
-
-
Save mukeshgurpude/25c6fb292893d0310d1bd9609042fcf3 to your computer and use it in GitHub Desktop.
sleeping-barber
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from threading import Thread | |
from time import sleep | |
def threaded(func): | |
def wrapper(*args, **kwargs): | |
thread = Thread(target=func, args=args, kwargs=kwargs) | |
thread.start() | |
return thread | |
return wrapper | |
class Barber: | |
def __init__(self, name): | |
self.name = name | |
self.queue = [] | |
self.is_working = False | |
@threaded | |
def work(self): | |
self.is_working = True | |
print(f"{self.name} is working") | |
while self.queue: | |
customer = self.queue.pop(0) | |
print(f"{self.name} is cutting hair of {customer.name}") | |
sleep(3) | |
customer.is_done = True | |
print(f"{self.name} is idle") | |
self.is_working = False | |
@threaded | |
def add_customer(self, customer): | |
self.queue.append(customer) | |
print(f"{customer.name} is waiting in the queue") | |
if not self.is_working: | |
self.work() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Customer: | |
def __init__(self, name, arrival_time) -> None: | |
self.name = name | |
self.arrival_time = arrival_time |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
0 | |
2 | |
2 | |
10 | |
11 | |
18 | |
23 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from barber import Barber | |
from customer import Customer | |
from threading import Thread | |
from time import sleep | |
def run(barber: Barber, file: str): | |
customer_arrival_times = [int(t.strip()) for t in open(file, 'r').readlines()] | |
for i, time in enumerate(customer_arrival_times): | |
customer = Customer(chr(65 + i), time) | |
barber.add_customer(customer) | |
if i < len(customer_arrival_times) - 1: | |
sleep(customer_arrival_times[i + 1] - time) | |
if __name__ == '__main__': | |
barber = Barber("Billu") | |
thread = Thread(target=run, args=(barber, 'input.txt')) | |
thread.start() | |
thread.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment