Python从普通函数中调用协程

Python从普通函数中调用协程

所以我有一个倒计时的脚本,看起来像这样:

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

我很困惑为什么要这么做。任何人都可以在这里解释我做错了什么吗?

最佳答案

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

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 时,您可以在单个OS的线程内有效地创建一个新的“执行线程”(请参阅​​光纤)。

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

10-11 15:46