gpt4 book ai didi

python - multiprocessing.pools.map_async 的回调不起作用?

转载 作者:太空狗 更新时间:2023-10-30 00:07:55 25 4
gpt4 key购买 nike

我似乎无法在使用 map_async() 时让我的回调工作。当我使用稍微修改过的代码来循环遍历我的数组时,它会通过 apply_async() 添加任务。从文档看来我应该能够将回调与 map_async() 一起使用,但也许这是某种新手错误...

from multiprocessing import Pool,TimeoutError
from time import sleep

servers=["s1","s2","s3","s4","s5","s6"]

def f(x):
print("start f(" + x + ")")
sleep(5)
print("end f(" + x + ")")
return "did " + x

def mycallback(x):
print("My callback " + str(x))

def myerrorcallback(r):
print("My errorcallback " + str(r))

if __name__ == '__main__':
pool = Pool(processes=4)
results = pool.map_async(f, servers, chunksize=1, callback=mycallback, error_callback=myerrorcallback)
print(results.get(timeout=11))

运行时我得到:

D:\python> f.py
start f(s1)
start f(s2)
start f(s3)
start f(s4)
end f(s1)
start f(s5)
end f(s2)
start f(s6)
end f(s4)
end f(s3)
end f(s5)
end f(s6)
['did s1', 'did s2', 'did s3', 'did s4', 'did s5', 'did s6']

当我将修改后的代码与 apply_async() 一起使用时,我从回调中获得了打印输出。修改后的代码只是将最后一部分改为:

if __name__ == '__main__':
pool = Pool(processes=4)
for server in servers:
pool.apply_async(f, (server,), callback=mycallback, error_callback=myerrorcallback)
pool.close()
pool.join()

结果:

D:\python\>fb.py
start f(s1)
start f(s2)
start f(s3)
start f(s4)
end f(s1)
start f(s5)
My callback did s1
end f(s2)
My callback did s2
start f(s6)
end f(s3)
My callback did s3
end f(s4)
My callback did s4
end f(s5)
My callback did s5
end f(s6)
My callback did s6

最佳答案

好吧,我捕获机会并为它记录了一个错误。事实证明这实际上是 3.3 中的一个错误,正在打补丁。

http://bugs.python.org/issue16307

关于python - multiprocessing.pools.map_async 的回调不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13043905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com