猿问

如果函数尚未完成,则使用超时返回

我有以下情况:


res = []


def longfunc(arg):

    # function runs arg number of steps

    # each step can take 500 ms to 2 seconds to complete

    # longfunc keeps adding result of each step into the array res 


def getResult(arg,timeout):

    # should call longfunc()

    # if longfunc() has not provided result by timeout milliseconds then return None

    # if there is partial result in res by timeout milliseconds then return res

    # if longfunc() ends before timeout milliseconds then return complete result of longfunc i.e. res array


result = getResult(2, 500)

我正在考虑使用multiprocessing.Process()放入longfunc()一个单独的进程,然后启动另一个线程休眠几timeout毫秒。我无法弄清楚如何在主线程中从它们两个中获得结果并决定哪个先出现。对这种方法或其他方法的任何建议表示赞赏。


千万里不及你
浏览 251回答 2
2回答

函数式编程

您可以使用time.perf_counter,您的代码将看到:import time&nbsp;ProcessTime = time.perf_counter&nbsp; #this returns nearly 0 when first call it if python version <= 3.6ProcessTime()&nbsp;def longfunc(arg, timeout):&nbsp; &nbsp; start = ProcessTime()&nbsp; &nbsp; while True&nbsp; &nbsp; &nbsp; &nbsp; # Do anything&nbsp; &nbsp; &nbsp; &nbsp; delta = start + timeout - ProcessTime()&nbsp; &nbsp; &nbsp; &nbsp; if delta > 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sleep(1)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return #Error or False&nbsp;&nbsp; &nbsp;&nbsp;您可以更改 While 对于每个任务的 for 循环,检查超时

一只萌萌小番薯

如果你正在应用 multiprocessing 那么你必须简单地应用p.join(timeout=5)where p in a process 这是一个简单的例子import timefrom itertools import countfrom multiprocessing import Processdef inc_forever():&nbsp; &nbsp; print('Starting function inc_forever()...')&nbsp; &nbsp; while True:&nbsp; &nbsp; &nbsp; &nbsp; time.sleep(1)&nbsp; &nbsp; &nbsp; &nbsp; print(next(counter))def return_zero():&nbsp; &nbsp; print('Starting function return_zero()...')&nbsp; &nbsp; return 0if __name__ == '__main__':&nbsp; &nbsp; # counter is an infinite iterator&nbsp; &nbsp; counter = count(0)&nbsp; &nbsp; p1 = Process(target=inc_forever, name='Process_inc_forever')&nbsp; &nbsp; p2 = Process(target=return_zero, name='Process_return_zero')&nbsp; &nbsp; p1.start()&nbsp; &nbsp; p2.start()&nbsp; &nbsp; p1.join(timeout=5)&nbsp; &nbsp; p2.join(timeout=5)&nbsp; &nbsp; p1.terminate()&nbsp; &nbsp; p2.terminate()if p1.exitcode is None:&nbsp; &nbsp; &nbsp; &nbsp;print(f'Oops, {p1} timeouts!')if p2.exitcode == 0:&nbsp; &nbsp; &nbsp; &nbsp; print(f'{p2} is luck and finishes in 5 seconds!')我想这可能对你有帮助
随时随地看视频慕课网APP

相关分类

Python
我要回答