SHARE
TWEET

Untitled

a guest Mar 23rd, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python3
  2.  
  3. import queue
  4. import threading
  5.  
  6.  
  7. class SingleThreadTaskRunner():
  8.     """
  9.     A task runner that runs tasks in the same sequence they were added
  10.     on a single thread.
  11.  
  12.     Its main advantage is that you can safely add tasks from various
  13.     threads and there will not be any races between those tasks.
  14.  
  15.     Example:
  16.         runner = SingleThreadTaskRunner(10)
  17.         while True:
  18.             runner.add_task(function_name, arg1, arg2)
  19.     """
  20.  
  21.     def __init__(self, max_queued_tasks):
  22.         self.queue = queue.Queue(max_queued_tasks)
  23.         self.thread = threading.Thread(target=self.worker)
  24.         self.thread.daemon = True
  25.         self.thread.start()
  26.  
  27.     def worker(self):
  28.         while True:
  29.             item = self.queue.get()
  30.             if item is None:
  31.                 break
  32.             task, args, kwargs = item
  33.             task(*args, **kwargs)
  34.             self.queue.task_done()
  35.  
  36.     def add_task(self, task, *args, **kwargs):
  37.         args = args or ()
  38.         kwargs = kwargs or {}
  39.         self.queue.put((task, args, kwargs))
  40.  
  41.     def join(self):
  42.         self.running = False
  43.         self.queue.put(None)
  44.         self.thread.join()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top