Skip to content

Instantly share code, notes, and snippets.

@ovuruska
Created March 11, 2022 11:18
Show Gist options
  • Select an option

  • Save ovuruska/4cbf7a73dbcacb3889950975aa6885ea to your computer and use it in GitHub Desktop.

Select an option

Save ovuruska/4cbf7a73dbcacb3889950975aa6885ea to your computer and use it in GitHub Desktop.
Parallel execution of blocking tasks.
from multiprocessing.pool import ThreadPool
from queue import Empty,Queue
class Executor:
def __init__(self,workers:int = 4,queue_size=8):
self.workers = workers
self.queue_size = queue_size
self.stop = False
self.queue = Queue(queue_size)
self.pool = ThreadPool(workers,self.worker)
def worker(self):
while not self.stop:
try:
func,args,kwargs = self.queue.get(True,2)
func(*args,**kwargs)
except Empty as e:
continue
except Exception as exp:
print(exp)
def add_func(self,func,*args,**kwargs):
self.queue.put([func,args,kwargs])
def close(self):
self.stop = True
self.pool.close()
self.pool.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment