ama*_*man 45 python-2.7 python-multiprocessing
使用map和有map_async什么区别?将项目从列表分发到4个进程后,它们是否没有运行相同的功能?
那么假设两者都在运行异步和并行是错误的吗?
def f(x):
return 2*x
p=Pool(4)
l=[1,2,3,4]
out1=p.map(f,l)
#vs
out2=p.map_async(f,l)
Run Code Online (Sandbox Code Playgroud)
qui*_*t3r 73
将作业映射到进程有四种选择.您必须考虑多参数,并发,阻塞和排序.map并且map_async仅在阻止方面有所不同.map_async是阻塞的map非阻塞
所以,假设你有一个功能
from multiprocessing import Pool
import time
def f(x):
print x*x
if __name__ == '__main__':
pool = Pool(processes=4)
pool.map(f, range(10))
r = pool.map_async(f, range(10))
# DO STUFF
print 'HERE'
print 'MORE'
r.wait()
print 'DONE'
Run Code Online (Sandbox Code Playgroud)
示例输出:
0
1
9
4
16
25
36
49
64
81
0
HERE
1
4
MORE
16
25
36
9
49
64
81
DONE
Run Code Online (Sandbox Code Playgroud)
pool.map(f, range(10))将等待所有10个函数调用完成,以便我们连续看到所有打印件.
r = pool.map_async(f, range(10))将以异步方式执行它们,并且仅在r.wait()被调用时阻塞,因此我们看到HERE并MORE介于两者之间,但DONE总是在最后.