PageRenderTime 105ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/merge/async_engine.py

https://github.com/funtoo/funtoo-overlay
Python | 55 lines | 44 code | 10 blank | 1 comment | 7 complexity | b6e99dfc68fffd5f9ea61d6733e32297 MD5 | raw file
  1. #!/usr/bin/python3
  2. import asyncio
  3. from concurrent.futures import ThreadPoolExecutor
  4. from collections import defaultdict
  5. from queue import Queue, Empty
  6. class AsyncEngine:
  7. queue_size = 60000
  8. def __init__(self, num_threads=40):
  9. self.task_q = Queue(maxsize=self.queue_size)
  10. self.num_threads = num_threads
  11. self.thread_exec = ThreadPoolExecutor(max_workers=self.num_threads)
  12. self.workers = []
  13. self.loop = asyncio.get_event_loop()
  14. self.keep_running = True
  15. def start_threads(self, enable_workers=True):
  16. if enable_workers is True:
  17. for x in range(0, self.num_threads):
  18. self.loop.run_in_executor(self.thread_exec, self._worker)
  19. print("Started %s workers." % self.num_threads)
  20. def add_worker(self, w):
  21. self.workers.append(self.thread_exec.submit(w))
  22. def enqueue(self, **kwargs):
  23. self.task_q.put(kwargs)
  24. def _worker(self):
  25. while self.keep_running is True or (self.keep_running is False and self.task_q.qsize() > 0 ):
  26. try:
  27. kwargs = defaultdict(lambda: None, self.task_q.get(timeout=3))
  28. self.worker_thread(**kwargs)
  29. except Empty:
  30. continue
  31. async def wait_for_workers_to_finish(self):
  32. self.keep_running = False
  33. await asyncio.gather(*self.workers)
  34. def exit_handler(self):
  35. """something for atexit.register"""
  36. self.loop.run_until_complete(asyncio.gather(
  37. asyncio.ensure_future(self.wait_for_workers_to_finish())
  38. ))
  39. def worker_thread(self, **kwargs):
  40. print("blarg")
  41. # vim: ts=4 sw=4 noet