【发布时间】:2019-06-12 13:12:56
【问题描述】:
我想在多个子流程中并行执行一些任务,如果任务没有在一定延迟内完成,则超时。
第一种方法是分叉和连接子进程单独,剩余超时根据全局超时计算,如this answer 中建议的那样。对我来说效果很好。
我想在这里使用的第二种方法是创建一个子进程池并等待全局超时,如this answer 中所建议的那样。
但是我对第二种方法有一个问题:在向子进程池提供具有 multiprocessing.Event() 对象的任务后,等待它们完成会引发此异常:
RuntimeError: Condition 对象只能通过继承在进程之间共享
这里是 Python 代码 sn-p:
import multiprocessing.pool
import time
class Worker:
def __init__(self):
self.event = multiprocessing.Event() # commenting this removes the RuntimeError
def work(self, x):
time.sleep(1)
return x * 10
if __name__ == "__main__":
pool_size = 2
timeout = 5
with multiprocessing.pool.Pool(pool_size) as pool:
result = pool.map_async(Worker().work, [4, 5, 2, 7])
print(result.get(timeout)) # raises the RuntimeError
【问题讨论】:
标签: python multiprocessing timeout pool