Beispiel #1
0
class ThreadPool:
    """ Pool of threads consuming tasks from a single queue """
    # queue of tasks
    tasks = None
    worker_threads = None

    def __init__(self, num_threads):
        self.tasks = Queue(num_threads)
        self.worker_threads = []
        for _ in range(num_threads):
            worker_thread = Worker(self.tasks)
            self.worker_threads.append(worker_thread)
            # start the worker thread
            worker_thread.start()

    def add_task(self, func, *args, **kargs):
        """ Add a task to the queue """
        self.tasks.put((func, args, kargs))

    def join(self):
        """ Wait for completion of all the tasks in the queue """
        self.tasks.join()
        # stop processing
        for worker_thread in self.worker_threads:
            worker_thread.is_running = False
        # join all threads
        for worker_thread in self.worker_threads:
            worker_thread.join()