Python 从普通函数调用协程

标签 python multithreading python-3.6 python-asyncio

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

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/

相关文章:

c# - 线程卷 #9000

python - 为什么使用 python F 字符串插值用引号引起来?

python - 在 Python 中仅使用 While 循环打印星号箭头

C# Regex "Verbose"就像在 Python 中一样

c++ - Windows 线程 : when should you use InterlockedExchangeAdd()?

python - 如何在类里面简化分数?

java - java Callable接口(interface)如何执行多任务

python - 错误 Python 子进程调用复制文件。没有文件,失败,但返回 1。为什么?

python - 如何有效地将函数应用于 Pandas 数据框的行?

python - 按日期排列的 Watson 对话日志