Advertisement
nirajs

republicans

Feb 5th, 2024
659
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.34 KB | None | 0 0
  1. import threading
  2. import time
  3. from collections import deque
  4.  
  5. class DriverSelection:
  6.  
  7.     def __init__(self):  # Corrected method name
  8.         self.republicans_queue = deque()
  9.         self.democrats_queue = deque()
  10.         self.cx = threading.Condition()
  11.         # Start the dispatcher thread
  12.         self.dispatcher_thread = threading.Thread(target=self.dispatcher, daemon=True)
  13.         self.dispatcher_thread.start()
  14.  
  15.     def request_cab(self, party):
  16.         with self.cx:
  17.             if party == "Republican":
  18.                 self.republicans_queue.append(threading.current_thread().name)
  19.             else:
  20.                 self.democrats_queue.append(threading.current_thread().name)
  21.  
  22.             print(f"{threading.current_thread().name} from {party} is requesting a cab.")
  23.  
  24.             self.cx.notify_all()  # Notify the dispatcher thread that a new member has arrived
  25.             self.cx.wait()  # Wait until the cab is dispatched
  26.  
  27.     def dispatcher(self):  # Made this an instance method by adding 'self'
  28.         while True:
  29.             with self.cx:
  30.                 # Check for 2-2, 4-0, or 0-4 combinations
  31.                 if (len(self.republicans_queue) >= 2 and len(self.democrats_queue) >= 2) or \
  32.                    (len(self.republicans_queue) == 4 and len(self.democrats_queue) == 0) or \
  33.                    (len(self.republicans_queue) == 0 and len(self.democrats_queue) == 4):
  34.  
  35.                     # Dispatch a cab and clear the queues accordingly
  36.                     if len(self.republicans_queue) >= 2 and len(self.democrats_queue) >= 2:
  37.                         for _ in range(2): self.republicans_queue.popleft()
  38.                         for _ in range(2): self.democrats_queue.popleft()
  39.                         print("Cab dispatched for 2 Republicans and 2 Democrats.")
  40.                     elif len(self.republicans_queue) == 4:
  41.                         for _ in range(4): self.republicans_queue.popleft()
  42.                         print("Cab dispatched for 4 Republicans.")
  43.                     else:
  44.                         for _ in range(4): self.democrats_queue.popleft()
  45.                         print("Cab dispatched for 4 Democrats.")
  46.  
  47.                     self.cx.notify_all()  # Notify all waiting threads that a cab has been dispatched
  48.                 else:
  49.                     self.cx.wait()  # Wait for new members to arrive
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement