gpt4 book ai didi

Python 从同步函数运行非阻塞异步函数

转载 作者:行者123 更新时间:2023-12-05 03:17:21 28 4
gpt4 key购买 nike

有没有一种方法可以从同步函数调用异步函数而无需等待它完成?

我当前的测试:

  1. 问题:WAITING test_timer_function 完成
async def test_timer_function():
await asyncio.sleep(10)
return

def main():
print("Starting timer at {}".format(datetime.now()))
asyncio.run(test_timer_function())
print("Ending timer at {}".format(datetime.now()))
  1. 问题:不调用 test_timer_function
async def test_timer_function():
await asyncio.sleep(10)
return

def main():
print("Starting timer at {}".format(datetime.now()))
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.ensure_future(test_timer_function())
print("Ending timer at {}".format(datetime.now()))

有什么建议吗?

最佳答案

异步函数实际上并不在后台运行:它们始终在单个线程中运行。

这意味着当异步代码(普通异步代码)中有并行任务时,只有当你给异步循环运行机会时,这些任务才会被执行——当你的代码使用 await< 时就会发生这种情况,调用 async forasync with 之一或从作为任务运行的协程函数返回。

在非异步代码中,您必须进入循环并将控制权传递给它,以便异步代码运行 - 这就是 asyncio.run 所做的 - 而 asyncio .ensure_future 不会:这个调用只是注册一个要执行的任务,只要 asyncio 循环有时间:但是你从函数返回而没有将控制权传递给异步循环,所以你的程序刚刚结束。

可以做的一件事是建立一个辅助线程,异步代码将在其中运行:该线程将运行其异步循环,您可以使用全局变量和普通线程数据结构(如队列)与其中的任务进行通信.

您的代码的最小更改是:

import asyncio
import threading

from datetime import datetime
now = datetime.now


async def test_timer_function():
await asyncio.sleep(2)
print(f"ending async task at {now()}")
return

def run_async_loop_in_thread():
asyncio.run(test_timer_function())

def main():
print(f"Starting timer at {now()}")
t = threading.Thread(target=run_async_loop_in_thread)
t.start()
print(f"Ending timer at {now()}")
return t

if __name__ == "__main__":
t = main()
t.join()
print(f"asyncio thread exited normally at {now()}")

(请在发布 Python 代码时,包括导入行和调用函数并使代码实际运行的行:它不像其他语言可能需要的大量样板,并完整地转换您的代码片段,准备运行,示例)

在控制台运行这段代码时的打印输出:

Starting timer at 2022-10-20 16:47:45.211654
Ending timer at 2022-10-20 16:47:45.212630
ending async task at 2022-10-20 16:47:47.213464
asyncio thread exited normally at 2022-10-20 16:47:47.215417

关于Python 从同步函数运行非阻塞异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74145286/

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