python ProcessPoolExecutor多进程并发

from concurrent.futures import ProcessPoolExecutor, as_completed
import random
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, 33) for _ in range(0, 10)]
if __name__ == '__main__':
    # with ProcessPoolExecutor(max_workers=3) as executor:
    #     futures = {executor.submit(fib, n):n for n in nums}
    #     for f in as_completed(futures):
    #       try:
    #         print('fib(%s) result is %s.' % (futures[f], f.result()))
    #       except Exception as e:
    #         print(e)

    with ProcessPoolExecutor(max_workers=3) 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)

猜你喜欢

转载自blog.csdn.net/qq_16792139/article/details/120162976