Pool of threads consuming tasks from a queue
| 17 | self.tasks.task_done() |
| 18 | |
| 19 | class ThreadPool: |
| 20 | """Pool of threads consuming tasks from a queue""" |
| 21 | def __init__(self, num_threads): |
| 22 | self.tasks = Queue(num_threads) |
| 23 | for _ in range(num_threads): Worker(self.tasks) |
| 24 | |
| 25 | def add_task(self, func, *args, **kargs): |
| 26 | """Add a task to the queue""" |
| 27 | self.tasks.put((func, args, kargs)) |
| 28 | |
| 29 | def wait_completion(self): |
| 30 | """Wait for completion of all the tasks in the queue""" |
| 31 | self.tasks.join() |
| 32 | |
| 33 | if __name__ == '__main__': |
| 34 | from random import randrange |