with futures.ThreadPoolExecutor(max_workers=4) as ex: print(list(ex.map(f, range(10))))
写法三,使用gevent库的ThreadPool
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# code from https://github.com/gevent/gevent/blob/master/examples/threadpool.py
import time import gevent from gevent.threadpool import ThreadPool
pool = ThreadPool(3) start = time.time() for _ inrange(4): pool.spawn(time.sleep, 1) gevent.wait() delay = time.time() - start print('Running "time.sleep(1)" 4 times with 3 threads. Should take about 2 seconds: %.3fs' % delay)
进程
MultiProcess
1 2 3 4 5 6 7 8 9 10 11 12 13
import multiprocessing
defworker(num): print("Worker: {}".format(num))
jobs = []
for i inrange(5): p = multiprocessing.Process(target=worker,args=(i,)) jobs.append(p) p.start()
ProcessPool
写法一,使用multiprocessing模块的Pool
1 2 3 4 5 6 7 8 9
from multiprocessing import Pool p = Pool(4)
deff(x): return x*x
print(p.map(f, range(10)))
写法二,使用multiprocessing模块的Pool以及上下文管理器With
1 2 3 4 5 6 7 8 9 10 11
from multiprocessing import Pool, TimeoutError import time import os
deff(x): return x*x
with Pool(processes=4) as pool: print(pool.map(f,range(10)))
写法三,使用concurrent模块的ProcessPoolExecutor以及with
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from concurrent import futures
deff(x): return x*x
with futures.ProcessPoolExecutor(max_workers=4) as ex: print(list(ex.map(f, range(10)))) # Also you can use ex.submit, and get it's value by result() method #for i in range(10): # res = ex.submit(f,i) # print(res.result())