gpt4 book ai didi

Python 从普通函数调用协程

转载 作者:行者123 更新时间:2023-11-30 22:19:48 24 4
gpt4 key购买 nike

所以我有一个倒计时脚本,如下所示:

import time, threading, asyncio
def countdown(n, m):
print("timer start")
time.sleep(n)
print("timer stop")
yield coro1

async def coro1():
print("coroutine called")

async def coromain():
print("first")
t1 = threading.Thread(target=countdown, args=(5, 0))
t1.start()
print("second")

loop = asyncio.get_event_loop()
loop.run_until_complete(coromain())
loop.stop()

我想要它做的很简单:

Run coromain
Print "first"
Start thread t1, print "timer start" and have it wait for 5 seconds
In the mean time, print "second"
after 5 seconds, print "timer stop"
exit

但是,当我运行此代码时,它会输出:

Run coromain
Print "first"
Print "second"
exit

我很困惑为什么要这样做。谁能解释一下我在这里做错了什么?

最佳答案

这取决于您的问题是否是施加额外约束的更大问题的一部分,但我不认为有理由使用线程。相反,您可以使用在同一事件循环中运行的两个单独的任务,这是异步编程的要点之一:

import asyncio

async def countdown(n, m): # <- coroutine function
print("timer start")
await asyncio.sleep(n)
print("timer stop")
await coro1()

async def coro1():
print("coroutine called")

async def coromain():
print("first")
asyncio.ensure_future(countdown(5, 0)) # create a new Task
print("second")

loop = asyncio.get_event_loop()
loop.run_until_complete(coromain()) # run coromain() from sync code
pending = asyncio.Task.all_tasks() # get all pending tasks
loop.run_until_complete(asyncio.gather(*pending)) # wait for tasks to finish normally

输出:

first
second
timer start
(5 second wait)
timer stop
coroutine called

当使用ensure_future时,您可以在单个操作系统的线程内有效地创建一个新的“执行线程”(请参阅​​纤程)。

关于Python 从普通函数调用协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48993459/

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