在Python中使用多处理池

user1867151:

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

    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)

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

查尔斯·兰道:

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

  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)

旧答案

这让我发疯了片刻,但是后来才有意义。

如果我用如下multiply更改运行它

def multiply(nums):
    print("print")
    return nums[0] * nums[1]

运行正常。您在评论中说:“我不认为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()

这使:

multiply() missing 1 required positional argument: 'y'

multiply像这样:

def multiply(nums):
    return nums[0] * nums[1]

然后返回 [1, 4, 9]

PS我正在运行Python 3.6.7

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章