Python从普通函数调用协程

2 python multithreading python-asyncio python-3.6

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

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 Code Online (Sandbox Code Playgroud)

我想要它做的很简单:

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 Code Online (Sandbox Code Playgroud)

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

Run coromain
Print "first"
Print "second"
exit
Run Code Online (Sandbox Code Playgroud)

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

Nor*_*ius 5

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

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
Run Code Online (Sandbox Code Playgroud)

输出:

first
second
timer start
(5 second wait)
timer stop
coroutine called
Run Code Online (Sandbox Code Playgroud)

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