第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果函數(shù)尚未完成,則使用超時返回

如果函數(shù)尚未完成,則使用超時返回

千萬里不及你 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毫秒。我無法弄清楚如何在主線程中從它們兩個中獲得結(jié)果并決定哪個先出現(xiàn)。對這種方法或其他方法的任何建議表示贊賞。
查看完整描述

2 回答

?
函數(shù)式編程

TA貢獻1807條經(jīng)驗 獲得超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 對于每個任務(wù)的 for 循環(huán),檢查超時


查看完整回答
反對 回復(fù) 2023-04-11
?
一只萌萌小番薯

TA貢獻1795條經(jīng)驗 獲得超7個贊

如果你正在應(yīng)用 multiprocessing 那么你必須簡單地應(yīng)用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!')

我想這可能對你有幫助


查看完整回答
反對 回復(fù) 2023-04-11
  • 2 回答
  • 0 關(guān)注
  • 226 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號