gpt4 book ai didi

python - 如果执行在超时内完成则从函数返回,否则进行回调

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:54 28 4
gpt4 key购买 nike

我有一个 Python 3.5 项目,没有使用任何异步功能。我必须实现以下逻辑:

def should_return_in_3_sec(some_serious_job, arguments, finished_callback):
# Start some_serious_job(*arguments) in a task
# if it finishes within 3 sec:
# return result immediately
# otherwise return None, but do not terminate task.
# If the task finishes in 1 minute:
# call finished_callback(result)
# else:
# call finished_callback(None)
pass

should_return_in_3_sec() 函数应该保持同步,但是我要编写任何新的异步代码(包括 some_serious_job())。

最优雅、最符合 Python 风格的方法是什么?

最佳答案

fork 一个正在做重要工作的线程,让它把结果写入队列,然后终止。从该队列中读取主线程,超时时间为三秒。如果发生超时,则启动另一个线程并返回 None。让第二个线程从队列中读取,超时时间为一分钟;如果也超时,请调用 finished_callback(None);否则调用 finished_callback(result)。

我画的是这样的:

import threading, queue

def should_return_in_3_sec(some_serious_job, arguments, finished_callback):
result_queue = queue.Queue(1)

def do_serious_job_and_deliver_result():
result = some_serious_job(arguments)
result_queue.put(result)

threading.Thread(target=do_serious_job_and_deliver_result).start()

try:
result = result_queue.get(timeout=3)
except queue.Empty: # timeout?

def expect_and_handle_late_result():
try:
result = result_queue.get(timeout=60)
except queue.Empty:
finished_callback(None)
else:
finished_callback(result)

threading.Thread(target=expect_and_handle_late_result).start()
return None
else:
return result

关于python - 如果执行在超时内完成则从函数返回,否则进行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42581175/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com