为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

千万里不及你 2023-04-11 15:41:01
我有以下情况: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 arrayresult = getResult(2, 500)我正在考虑使用multiprocessing.Process()放入longfunc()一个单独的进程,然后启动另一个线程休眠几timeout毫秒。我无法弄清楚如何在主线程中从它们两个中获得结果并决定哪个先出现。对这种方法或其他方法的任何建议表示赞赏。
查看完整描述

2 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

您可以使用time.perf_counter,您的代码将看到:


import time 

ProcessTime = time.perf_counter  #this returns nearly 0 when first call it if python version <= 3.6

ProcessTime() 

def longfunc(arg, timeout):

    start = ProcessTime()

    while True

        # Do anything

        delta = start + timeout - ProcessTime()

        if delta > 0:

            sleep(1)

        else:

            return #Error or False 

    

您可以更改 While 对于每个任务的 for 循环,检查超时


查看完整回答
反对 回复 2023-04-11
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

如果你正在应用 multiprocessing 那么你必须简单地应用p.join(timeout=5)where p in a process 这是一个简单的例子


import time

from itertools import count

from multiprocessing import Process

def inc_forever():

    print('Starting function inc_forever()...')

    while True:

        time.sleep(1)

        print(next(counter))

def return_zero():

    print('Starting function return_zero()...')

    return 0

if __name__ == '__main__':

    # counter is an infinite iterator

    counter = count(0)

    p1 = Process(target=inc_forever, name='Process_inc_forever')

    p2 = Process(target=return_zero, name='Process_return_zero')

    p1.start()

    p2.start()

    p1.join(timeout=5)

    p2.join(timeout=5)

    p1.terminate()

    p2.terminate()

if p1.exitcode is None:

       print(f'Oops, {p1} timeouts!')

if p2.exitcode == 0:

        print(f'{p2} is luck and finishes in 5 seconds!')

我想这可能对你有帮助


查看完整回答
反对 回复 2023-04-11
  • 2 回答
  • 0 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信