Advertisement
androxgh0st

thread

Mar 15th, 2020
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. from Queue import Queue
  2. from threading import Thread
  3.  
  4. class Worker(Thread):
  5. def __init__(self, tasks):
  6. Thread.__init__(self)
  7. self.tasks = tasks
  8. self.daemon = True
  9. self.start()
  10.  
  11. def run(self):
  12. while True:
  13. func, args, kargs = self.tasks.get()
  14. try: func(*args, **kargs)
  15. except Exception, e: print e
  16. self.tasks.task_done()
  17.  
  18. class ThreadPool:
  19. def __init__(self, num_threads):
  20. self.tasks = Queue(num_threads)
  21. for _ in range(num_threads): Worker(self.tasks)
  22.  
  23. def add_task(self, func, *args, **kargs):
  24. self.tasks.put((func, args, kargs))
  25.  
  26. def wait_completion(self):
  27. self.tasks.join()
  28.  
  29. pool = ThreadPool(25)
  30. pool.add_task(function, value)
  31. pool.wait_completion()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement