Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- import time
- from collections import deque
- class DriverSelection:
- def __init__(self): # Corrected method name
- self.republicans_queue = deque()
- self.democrats_queue = deque()
- self.cx = threading.Condition()
- # Start the dispatcher thread
- self.dispatcher_thread = threading.Thread(target=self.dispatcher, daemon=True)
- self.dispatcher_thread.start()
- def request_cab(self, party):
- with self.cx:
- if party == "Republican":
- self.republicans_queue.append(threading.current_thread().name)
- else:
- self.democrats_queue.append(threading.current_thread().name)
- print(f"{threading.current_thread().name} from {party} is requesting a cab.")
- self.cx.notify_all() # Notify the dispatcher thread that a new member has arrived
- self.cx.wait() # Wait until the cab is dispatched
- def dispatcher(self): # Made this an instance method by adding 'self'
- while True:
- with self.cx:
- # Check for 2-2, 4-0, or 0-4 combinations
- if (len(self.republicans_queue) >= 2 and len(self.democrats_queue) >= 2) or \
- (len(self.republicans_queue) == 4 and len(self.democrats_queue) == 0) or \
- (len(self.republicans_queue) == 0 and len(self.democrats_queue) == 4):
- # Dispatch a cab and clear the queues accordingly
- if len(self.republicans_queue) >= 2 and len(self.democrats_queue) >= 2:
- for _ in range(2): self.republicans_queue.popleft()
- for _ in range(2): self.democrats_queue.popleft()
- print("Cab dispatched for 2 Republicans and 2 Democrats.")
- elif len(self.republicans_queue) == 4:
- for _ in range(4): self.republicans_queue.popleft()
- print("Cab dispatched for 4 Republicans.")
- else:
- for _ in range(4): self.democrats_queue.popleft()
- print("Cab dispatched for 4 Democrats.")
- self.cx.notify_all() # Notify all waiting threads that a cab has been dispatched
- else:
- self.cx.wait() # Wait for new members to arrive
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement