Skip to content

Instantly share code, notes, and snippets.

@james4388
Created July 20, 2019 00:27
Show Gist options
  • Save james4388/218e8657dbe49169e0b58ad68a1e7052 to your computer and use it in GitHub Desktop.
Save james4388/218e8657dbe49169e0b58ad68a1e7052 to your computer and use it in GitHub Desktop.
Thread/Process runner helper. (pre async era)
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def task_runner(opts):
if isinstance(opts, (list, tuple)):
num_opts = len(opts)
args = None
kwargs = None
if num_opts == 2:
fn, args = opts
elif num_opts == 3:
fn, args, kwargs = opts
return fn(*(args or []), **(kwargs or {}))
if callable(opts):
return opts()
def run_concurrent(funcs, run_on_process=False, max_workers=4):
""" Run all funcs (fn, args, kwargs) and return result in order """
ExeClass = ThreadPoolExecutor
if run_on_process:
ExeClass = ProcessPoolExecutor
with ExeClass(max_workers=max_workers) as exe:
results = exe.map(task_runner, funcs)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment