您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何启动协程并继续同步任务?

5b51 2022/1/14 8:21:38 python 字数 2811 阅读 522 来源 www.jb51.cc/python

我试图了解asyncio和端口我的线程未定.我将以两个无限运行的线程和一个非线程循环(所有这些都输出到控制台)为例.线程版本是import threading import time def a(): while True: time.sleep(1) print('a') def b(): while T

概述

我试图了解asyncio和端口我的线程未定.我将以两个无限运行的线程和一个非线程循环(所有这些都输出到控制台)为例.

线程版本是

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线程.

然后我希望至少有两个并行运行的第一个线程(a和b)(最坏的情况是,将第三个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()协程.是不是应该启动a()并返回执行(然后启动b())?

考虑这个例子:

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()

总结

以上是编程之家为你收集整理的如何启动协程并继续同步任务?全部内容,希望文章能够帮你解决如何启动协程并继续同步任务?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶