Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import queue
- import threading
- class SingleThreadTaskRunner():
- """
- A task runner that runs tasks in the same sequence they were added
- on a single thread.
- Its main advantage is that you can safely add tasks from various
- threads and there will not be any races between those tasks.
- Example:
- runner = SingleThreadTaskRunner(10)
- while True:
- runner.add_task(function_name, arg1, arg2)
- """
- def __init__(self, max_queued_tasks):
- self.queue = queue.Queue(max_queued_tasks)
- self.thread = threading.Thread(target=self.worker)
- self.thread.daemon = True
- self.thread.start()
- def worker(self):
- while True:
- item = self.queue.get()
- if item is None:
- break
- task, args, kwargs = item
- task(*args, **kwargs)
- self.queue.task_done()
- def add_task(self, task, *args, **kwargs):
- args = args or ()
- kwargs = kwargs or {}
- self.queue.put((task, args, kwargs))
- def join(self):
- self.running = False
- self.queue.put(None)
- self.thread.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement