【发布时间】:2017-08-04 14:37:48
【问题描述】:
Python concurrent.futures 和 ProcessPoolExecutor 提供了一个简洁的界面来安排和监控任务。期货甚至 provide 一个 .cancel() 方法:
cancel():尝试取消通话。如果调用当前正在执行且无法取消,则该方法将返回 False,否则该调用将被取消,该方法将返回 True。
不幸的是,在类似的question(关于 asyncio)中,答案声称使用此文档片段无法取消正在运行的任务,但只有当它们正在运行且不可取消时,文档才这么说。
向进程提交 multiprocessing.Events 也不是一件容易的事(通过参数这样做,如在 multiprocess.Process 中返回一个 RuntimeError)
我想做什么?我想对搜索空间进行分区并为每个分区运行一个任务。但是拥有一个解决方案就足够了,而且该过程是 CPU 密集型的。那么,有没有一种真正舒适的方法来实现这一点,并且不会通过使用 ProcessPool 来抵消收益?
例子:
from concurrent.futures import ProcessPoolExecutor, FIRST_COMPLETED, wait
# function that profits from partitioned search space
def m_run(partition):
for elem in partition:
if elem == 135135515:
return elem
return False
futures = []
# used to create the partitions
steps = 100000000
with ProcessPoolExecutor(max_workers=4) as pool:
for i in range(4):
# run 4 tasks with a partition, but only *one* solution is needed
partition = range(i*steps,(i+1)*steps)
futures.append(pool.submit(m_run, partition))
done, not_done = wait(futures, return_when=FIRST_COMPLETED)
for d in done:
print(d.result())
print("---")
for d in not_done:
# will return false for Cancel and Result for all futures
print("Cancel: "+str(d.cancel()))
print("Result: "+str(d.result()))
【问题讨论】:
-
您可以尝试将
Event设置为全局变量,而不是将其作为参数传递,参见stackoverflow.com/questions/1675766/… -
@niemmi 谢谢你的提示。我可能会尝试将此作为一种解决方法,因为它在调用不同模块时感觉设计得不好。
-
也许这一切都与没有立即取消 POSIX API 的事实有关:stackoverflow.com/questions/2084830/…
标签: python multiprocess concurrent.futures