超时多处理函数 [英] Timing out a multiprocessing function
问题描述
我需要为使用一些多处理内容的 python 函数设置时间限制(我不知道这是否重要).像这样:
I need to set a time limit on a python function which use some multiprocessing stuff (I don't know if it matters). Something like this:
function(a_list):
p1 = Process(a_list[0:len(a_list/2)])
p2 = Process(a_list[len(a_list)/2: len(a_list)])
//start and join p1, p2
我环顾网络,发现了一个超时装饰器,但它看起来非常棘手和冗长(我是装饰器的新手).我想要的是一件简单的事情.
I look around the net and I found a time out decorator but it looks quite tricky and verbose (I'm newbie on decorators). What I'd want is a simple thing.
我觉得我说得太简单了.我的程序迭代上述函数并将结果存储在一个列表中,如下所示:
I think I made it too simple. My program iterates over the above function and store result in a list something like this:
while(something):
retval = function(some_list) # here I need the time out thing
# if function timed out then skip
ris_list.append(retval)
推荐答案
您应该可以使用以下代码做到这一点:
You should be able to do that with this code:
process.join(timeout)
if process.is_alive():
process.terminate()
因此,不是在函数中设置超时,您可以加入超时进程,如果该进程在超时后还没有完成,则终止它.
So instead of setting a timeout in the function, you can join with a timeout the process and if the process hasn't finished after that timeout, then terminate it.
这篇关于超时多处理函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!