Skip to main content
 首页 » 编程设计

python之Pool.map 与 Pool.map_async

2025年04月02日33davidwang456

我有这样的程序:

from multiprocessing import Pool 
import time 
 
def f(x): 
# I make a heavy code here to take time 
  for i in range(10000): 
     for i in range(10000): 
        pass #do nothing 
 
  print x #print 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' 

据我所知,pool.map 会按顺序返回,而 pool.map_async 不会。 我试图弄清楚它们之间的区别,但我还没有弄清楚。

实际上,我已经阅读了一些帖子,例如:Python multiprocessing : map vs map_async

但我还是很困惑。 我的问题是:

  1. 这两个功能有何区别?
  2. 当我运行上面的代码时,我得到了这个:

1 3 2 0 4 6 5 7 8 9 HERE MORE 1 0 3 2 5 4 6 7 8 9 Done

我希望 pool.map 会按顺序返回输出,但它没有! 那么,为什么它没有按顺序返回呢?还是我误解了函数?

  1. 我认为当 pool.map 被调用时,主要的(下面的代码,比如
    r = pool.map_async(f, range(10)); 打印'这里'; 打印“更多” 正在继续运行。所以我希望数字之间印有“这里”和“更多”,我的意思是像

3 2 0 4 6 HERE 5 7 8 9 1 0 3 2 MORE 5 4 6 7 8 9 Done

但它以其他方式发生了。 为什么它没有按预期运行?

  1. 如果我注释重代码,f 函数现在就是:

    def f(x): 打印x

然后这两个函数将按顺序返回输出(我尝试运行了很多次,它总是打印相同的结果。 那么,为什么它在有/没有重代码时表现不同。

如有任何帮助,我们将不胜感激。 谢谢。

请您参考如下方法:

from multiprocessing import Pool 
import time 
 
def f(x): 
# I make a heavy code here to take time 
  for i in range(10000): 
     for i in range(10000): 
        pass #do nothing 
  print x 
  return x  
 
if __name__ == '__main__': 
  pool = Pool(processes=4) 
 
  print pool.map(f, range(10)) 
  r  = pool.map_async(f, range(10)) 
 
  # DO STUFF 
  print 'HERE' 
  print 'MORE' 
  r.wait() 
  print 'Done' 
  print r.get() 
  1. pool.map_async 不会阻止您的脚本,而 pool.map 会(如 quikst3r 所述)。
  2. 我稍微调整了您的脚本以使其更具说明性。如您所见,最终结果都是有序的,除了在启动 pool.map_async 之后还会执行后续代码。输出是:

    1 
    3 
    0 
    2 
    4 
    5 
    7 
    6 
    8 
    9 
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
    HERE 
    MORE 
    3 
    2 
    1 
    0 
    5 
    4 
    6 
    7 
    8 
    9 
    Done 
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
    

由于作业分配的开销和 cpu 的单独负载,打印顺序很难确定。