Last active
November 4, 2021 09:53
-
-
Save ixsluo/57b44214f5e620779f8dc6b21844ff6d to your computer and use it in GitHub Desktop.
进程池
This file contains 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
import multiprocessing as mp | |
from tqdm import tqdm | |
class MyProcessPool(): | |
def __init__(self, processes, timeout=None, error_callback=None): | |
self.pool = mp.Pool(processes=processes) | |
self.timeout = timeout | |
self.error_callback = error_callback | |
def work(self, job, args_list): | |
p_list, results = [], [] | |
with tqdm(total=len(args_list)) as pbar: | |
def callback(*args, **kargs): # update pbar | |
pbar.update() | |
for args in args_list: | |
p = self.pool.apply_async( | |
job, args, callback=callback, error_callback=self.error_callback) | |
p_list.append(p) | |
self.pool.close() | |
for p in p_list: | |
try: | |
res = p.get(timeout=self.timeout) | |
except mp.TimeoutError: | |
pass | |
else: | |
results.append(res) | |
self.pool.terminate() # terminate unfinished jobs | |
return results | |
def job(*args): | |
return args |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment