Skip to content

Instantly share code, notes, and snippets.

@davidmoremad
Last active April 28, 2022 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidmoremad/bc9ea106e01804ec030165fdac4fcd56 to your computer and use it in GitHub Desktop.
Save davidmoremad/bc9ea106e01804ec030165fdac4fcd56 to your computer and use it in GitHub Desktop.
Simple class for Threading with Queues
# -*- coding: utf-8 -*-
from threading import Thread
from queue import Queue
class Worker(Thread):
"""
Thread executing tasks from a given tasks queue
http://code.activestate.com/recipes/577187-python-thread-pool/
"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception as e: print(e)
self.tasks.task_done()
class ThreadPool:
"""
Pool of threads consuming tasks from a queue
http://code.activestate.com/recipes/577187-python-thread-pool/
"""
def __init__(self, num_threads):
self.tasks = 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