https://www.cnblogs.com/mylu/p/11247125.html
ProcessPoolExecutor多进程并发任务管理
from concurrent.futures import ProcessPoolExecutor, as_completed import random import time def fib(n): if n > 30: raise Exception('can not > 30, now %s' % n) if n <= 2: return 1 return fib(n - 1) + fib(n - 2) nums = [random.randint(0, 10) for _ in range(0, 10)] if __name__ == '__main__': with ProcessPoolExecutor(max_workers=4) as executor: futures = {} for n in nums: job = executor.submit(fib, n) futures[job] = n # as_completed()方法是一个生成器,在没有任务完成的时候,会阻塞, # 在有某个任务完成的时候,会yield这个任务,就能执行for循环下面的语句,然后继续阻塞住,循环到所有的任务结束。从结果也可以看出,先完成的任务会先通知主线程。 for job in as_completed(futures): try: re = job.result() n = futures[job] print('fib(%s) result is %s.' % (n, re)) except Exception as e: print(e)
原创文章,转载请注明出处:http://124.221.219.47/article/78961/