Python 如何为使用多处理的函数设置超时?

Python 如何为使用多处理的函数设置超时?,python,multiprocessing,timeout,Python,Multiprocessing,Timeout,我有一个函数,它使用多处理.pool来执行一些繁重的计算(使用sleep(5)建模),如果计算时间过长,我希望有一个超时来结束此计算,并提前关闭池 def add_const(number, const): print('Adding', const,'to', number) time.sleep(5) return number+const def function_parallel(list_of_numbers, const): pool = Pool(2

我有一个函数,它使用
多处理.pool
来执行一些繁重的计算(使用
sleep(5)
建模),如果计算时间过长,我希望有一个超时来结束此计算,并提前关闭池

def add_const(number, const):
    print('Adding', const,'to', number)
    time.sleep(5)
    return number+const
def function_parallel(list_of_numbers, const):
    pool = Pool(2)
    data=pool.imap(functools.partial(add_const, const=const), list_of_numbers)
    pool.close()
    pool.join()
    return(data)
我尝试使用
stopit
module(),但没有成功

t1 = time.time()
with stopit.ThreadingTimeout(2) as to_ctx_mgr:
    assert to_ctx_mgr.state == to_ctx_mgr.EXECUTING
    result=[]
    data=function_parallel([1, 2], 2)
    for i in data:
        result.append(i)
if to_ctx_mgr.state == to_ctx_mgr.TIMED_OUT:
    result.append('timeout')
print(result)
print(time.time()-t1)
函数_parallel
中使用
map
时,它花费了整整5秒的时间,而不是在2秒后停止,而且它还离开了僵尸进程。 由于
imap
计算被冻结,不得不被迫停止,因此情况更糟

是否有安全可靠的方法来超时此功能?谢谢

编辑:

不幸的是,我无法将
pebble
应用于我的问题。它允许为
add_const
的每个调用设置超时,并且我需要为整个池设置一个超时(例如,如果有一百万个调用,每个调用都很短,但加在一起需要很多时间)


更重要的是,一般来说,我希望对代码的很大一部分(包括池)进行超时(有时超时甚至可能发生在池之前),但似乎没有解决方案…

相关,这是否回答了您的问题?其他副本:相关,这是否回答了您的问题?其他副本: