Skip to content

Instantly share code, notes, and snippets.

@nelsnelson
Created August 29, 2014 04:26
Show Gist options
  • Save nelsnelson/74e894754db2c1cb0a54 to your computer and use it in GitHub Desktop.
Save nelsnelson/74e894754db2c1cb0a54 to your computer and use it in GitHub Desktop.
class Worker(threading.Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
threading.Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
try:
func, args, kargs = self.tasks.get()
func(*args, **kargs)
self.tasks.task_done()
except KeyboardInterrupt as ex:
print "\nInterrupted"
sys.exit(0)
except Exception as ex:
print(traceback.format_exc())
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue.Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment