Created
July 20, 2019 00:27
-
-
Save james4388/218e8657dbe49169e0b58ad68a1e7052 to your computer and use it in GitHub Desktop.
Thread/Process runner helper. (pre async era)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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