Guest User

Untitled

a guest
Jun 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. import sys
  2. IS_PY2 = sys.version_info < (3, 0)
  3.  
  4. if IS_PY2:
  5. from Queue import Queue
  6. else:
  7. from queue import Queue
  8.  
  9. from threading import Thread
  10.  
  11.  
  12. class Worker(Thread):
  13. """ Thread executing tasks from a given tasks queue """
  14. def __init__(self, tasks):
  15. Thread.__init__(self)
  16. self.tasks = tasks
  17. self.daemon = True
  18. self.start()
  19.  
  20. def run(self):
  21. while True:
  22. func, args, kargs = self.tasks.get()
  23. try:
  24. func(*args, **kargs)
  25. except Exception as e:
  26. # An exception happened in this thread
  27. print(e)
  28. finally:
  29. # Mark this task as done, whether an exception happened or not
  30. self.tasks.task_done()
  31.  
  32.  
  33. class ThreadPool:
  34. """ Pool of threads consuming tasks from a queue """
  35. def __init__(self, num_threads):
  36. self.tasks = Queue(num_threads)
  37. for _ in range(num_threads):
  38. Worker(self.tasks)
  39.  
  40. def add_task(self, func, *args, **kargs):
  41. """ Add a task to the queue """
  42. self.tasks.put((func, args, kargs))
  43.  
  44. def map(self, func, args_list, kwargs_list=None):
  45. """ Add a list of tasks to the queue """
  46. no_kwargs = kwargs_list is None
  47. inputs = args_list if no_kwargs else zip(args_list, kwargs_list)
  48. for inp in inputs:
  49. if no_kwargs:
  50. self.add_task(func, *inp)
  51. else:
  52. self.add_task(func, *inp[0], **inp[1])
  53.  
  54. def wait_completion(self):
  55. """ Wait for completion of all the tasks in the queue """
  56. self.tasks.join()
  57.  
  58.  
  59. if __name__ == "__main__":
  60. from random import randrange
  61. from time import sleep
  62.  
  63. # Function to be executed in a thread
  64. def wait_delay(d, extra, kw=None):
  65. print("sleeping for (%d)sec" % d)
  66. print(kw)
  67. sleep(d)
  68.  
  69. # Generate random delays and other arguments
  70. num_inp = 20
  71. delays = [[randrange(3, 7) for j in range(2)] for i in range(num_inp)]
  72. kwargs = [{'kw':7} for j in range(num_inp)]
  73.  
  74. # Instantiate a thread pool with 5 worker threads
  75. pool = ThreadPool(5)
  76.  
  77. # Add the jobs in bulk to the thread pool. Alternatively you could use
  78. # `pool.add_task` to add single jobs. The code will block here, which
  79. # makes it possible to cancel the thread pool with an exception when
  80. # the currently running batch of workers is finished.
  81. pool.map(wait_delay, delays, kwargs)
  82. pool.wait_completion()
Add Comment
Please, Sign In to add comment