在Python中使用多处理池

use*_*151 8 python multiprocessing

有人可以指出此代码段出了什么问题。它没有给出任何结果。

    import multiprocessing

results = []
def log_results(result):
    results.append(result)


def multiply(x, y):
    print(f"Gets here for process name {multiprocessing.current_process().name()}")
    return x * y

if __name__ == "__main__":
    pool = multiprocessing.Pool()
    numbers = [(1,1), (2,2), (3,3)]
    for x, y in numbers:
        print (f"Checking x {x} and y {y}")
        pool.apply_async(multiply, (x, y), callback=log_results)
    pool.close()
    pool.join()
    print(results)
Run Code Online (Sandbox Code Playgroud)

结果是一个空列表,在这种情况下不应该对吗?我已经使用了apply_async和map_async。两者都没有给出正确的输出。有人可以帮我吗

Cha*_*dau 5

编辑:您对代码进行了编辑,所以现在我下面的答案已过时。我认为唯一需要做的两件事是:

  1. 添加一个error_callback因为我仍然认为您需要确保写入的池在默认情况下不会静默失败。
  2. 重写multiprocessing.current_process().name()multiprocessing.current_process().name.

所以:

import multiprocessing

results = []
def log_results(result):
    results.append(result)

def log_e(e):
  print(e)

def multiply(x, y):
    print(f"Gets here for process name {multiprocessing.current_process().name}")
    return x * y


pool = multiprocessing.Pool()
numbers = [(1,1), (2,2), (3,3)]
for x, y in numbers:
    print (f"Checking x {x} and y {y}")
    pool.apply_async(multiply, (x, y), callback=log_results,
                     error_callback=log_e)
pool.close()
pool.join()
print(results)
Run Code Online (Sandbox Code Playgroud)

旧答案

这让我发疯了一会儿,但后来它是有道理的。

如果我以multiply这样的方式运行它:

def multiply(nums):
    print("print")
    return nums[0] * nums[1]
Run Code Online (Sandbox Code Playgroud)

它运行良好。您在评论中说“我不认为该函数首先multiply被调用。” 这是因为有callback指定但没有error_callback指定。省略错误回调的结果是您的脚本无声无息地失败。

您可以通过以下方式检查:

import multiprocessing

results = []
def log_results(result):
    print(result)

def log_e(e):
  print(e)

def multiply(x, y):
    print(f"Gets here for process name {multiprocessing.current_process().name()}")
    return x * y

pool = multiprocessing.Pool()
numbers = [[1,1], [2,2], [3,3]]
mapResult = pool.map_async(multiply, numbers, callback=log_results,
                           error_callback=log_e)

pool.close()
pool.join()
Run Code Online (Sandbox Code Playgroud)

这使:

multiply() missing 1 required positional argument: 'y'
Run Code Online (Sandbox Code Playgroud)

而随着multiply像这样:

def multiply(nums):
    return nums[0] * nums[1]
Run Code Online (Sandbox Code Playgroud)

然后它返回 [1, 4, 9]

PS我正在运行Python 3.6.7