apply_async 的有序结果

Ordered results with apply_async

我读到函数 apply_async 没有给出有序的结果。如果我重复调用打印数字列表的平方的函数,我可以从显示中看到该列表未排序。

然而,当函数 returns 数字而不是打印它并且我使用 .get() 获取值时,我看到结果是有序的。

我有几个问题--

  1. 为什么 .get() 的结果是有序的?
  2. 如果我有一个循环,它作为一个名为 a 的变量,并且它的值对于不同的迭代是不同的。使用 apply_async 是否会导致覆盖 a 的值,因为它 运行 是并行和异步的进程?
  3. 如果我 运行 apply 而不是 apply_async 是否可以节省计算时间?我的代码显示 apply 比 for 循环慢。为什么会这样?
  4. 我们可以将 ___main___ 函数中声明的函数与 apply_async 一起使用吗?

这是一个小的工作示例:

from multiprocessing import Pool
import time

def f(x):
    return x*x

if __name__ == '__main__':
    
    print('For loop')
    t1f = time.time()
    for ii in range(20):
        f(ii)
    t2f = time.time()    
    print('Time taken for For loop = ', t2f-t1f,' seconds')
    
    pool = Pool(processes=4)
    print('Apply async loop')
    t1a = time.time()
    results = [pool.apply_async(f, args = (j,)) for j in range(20)]

    pool.close()
    pool.join()
    t2a = time.time()    
    print('Time taken for pool = ', t2a-t1a,' seconds')
    print([results[hh].get() for hh in range(len(results))])

结果为:

For loop Time taken for For loop = 5.9604644775390625e-06 seconds

Apply async loop Time taken for pool = 0.10188460350036621 seconds

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

  1. Why are the results from .get() ordered?

因为 results 列表是有序的。

  1. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause overwrites of the values of a as it runs the processes in parallel and asynchronously?

一般不会,但不看代码我就不知道了。

  1. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for loop. Why is that so?

不,apply 每次调用都会阻塞,没有并行性。 apply 由于多处理开销较慢。

  1. Can we use a function declared within the ___main___ function with apply_async?

*nix 是,windows 不是,因为没有 fork()

.apply_async的时间测量是错误的,你应该在result.get之后取t2a,不要假设结果是按顺序完成的:

while not all(r.ready() for r in results):
    time.sleep(0.1)

顺便说一句,你的工作函数运行得太快无法完成,做更多的计算来做一个真正的基准测试。