Source code for tagit.thread_pool

"""

Part of the tagit module.
A copy of the license is provided with the project.
Author: Matthias Baumgartner, 2016

"""

# STANDARD IMPORTS
import threading

# EXPORTS
__all__ = ('ThreadPool', )

## CODE ##

[docs]class ThreadPool(object): """ """ def __init__(self, pool_size=1): self.pool_size = max(pool_size, 1) self.blocker = threading.Semaphore(self.pool_size) self.num_active = 0
[docs] def add_task(self, task, *args, **kwargs): """Add a callable *task* to the queue. The callback is executed as soon as there's a free worker in the pool. Until then, the call to *add_task* is blocking. Additional arguments are passed to the *task*. """ if self.pool_size == 1: # Optimization if there's no real pool self.num_active = 1 task(*args, **kwargs) self.num_active = 0 else: def worker(): """Encapsulates the task, signals when finished.""" self.num_active += 1 task(*args, **kwargs) self.num_active -= 1 self.blocker.release() # Release slot self.blocker.acquire() # Wait until there's a free slot threading.Thread(target=worker).start()
[docs] def get_active(self): """Return the number of active workers.""" return self.num_active
[docs] def get_pool_size(self): """Return the pool size.""" return self.pool_size ## EOF ##