【问题标题】:How to start coroutines and continue with synchronous tasks?如何启动协程并继续同步任务?
【发布时间】:2017-08-20 19:09:40
【问题描述】:

我试图了解asyncio 并表达我对threading 的不理解。我将以两个无限运行的线程和一个非线程循环(它们都输出到控制台)为例。

threading 版本是

import threading
import time

def a():
    while True:
        time.sleep(1)
        print('a')

def b():
    while True:
        time.sleep(2)
        print('b')

threading.Thread(target=a).start()
threading.Thread(target=b).start()
while True:
        time.sleep(3)
        print('c')

我现在尝试根据documentation 将此移植到asyncio

问题 1:我不明白如何添加非线程任务,因为我看到的所有示例都在程序末尾显示了一个持续循环,该循环控制 asyncio 线程。

然后我希望至少有两个第一个线程(ab)并行运行(并且,最坏的情况,将第三个 c 添加为线程,放弃混合线程的想法和非线程操作):

import asyncio
import time

async def a():
    while True:
        await asyncio.sleep(1)
        print('a')

async def b():
    while True:
        await asyncio.sleep(2)
        print('b')

async def mainloop():
    await a()
    await b()

loop = asyncio.get_event_loop()
loop.run_until_complete(mainloop())
loop.close()

问题2:输出是a的序列,说明b()协程根本没有被调用。 await 不是应该启动 a() 并返回执行(然后启动 b())吗?

【问题讨论】:

    标签: python multithreading asynchronous async-await python-asyncio


    【解决方案1】:

    await 在某个点停止执行,您执行await a(),并且您在a() 中有一个无限循环,因此逻辑上的b() 不会被调用。想一想,就像在 mainloop() 中插入 a()

    考虑这个例子:

    async def main():
        while True:
            await asyncio.sleep(1)
            print('in')
    
        print('out (never gets printed)')
    

    要实现您想要的,您需要创建一个可以管理多个协程的未来。 asyncio.gather 就是为了这个。

    import asyncio
    
    
    async def a():
        while True:
            await asyncio.sleep(1)
            print('a')
    
    
    async def b():
        while True:
            await asyncio.sleep(2)
            print('b')
    
    
    async def main():
        await asyncio.gather(a(), b())
    
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
    

    【讨论】:

    • 谢谢丹尼尔。如果我做对了,那么我必须同时启动我所有的协程(通过.gather()),而threading(启动一个线程,做某事,启动另一个线程,......)可能不是使用 `asyncio` 可以了吗?
    • 好的,我已经投了赞成票,稍等片刻,希望有一个解决协程分离启动的方法,否则你的很好,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多