加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 22:32:29 所属栏目:Python 来源:网络整理
导读:我试图了解asyncio和端口我的线程未定.我将以两个无限运行的线程和一个非线程循环(所有这些都输出到控制台)为例. 线程版本是 import threadingimport timedef a(): while True: time.sleep(1) print('a')def b(): while True: time.sleep(2) print('b')threa

我试图了解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())?

最佳答案
等待在某一点停止执行,你等待一个(),并且你在()中有一个无限循环,所以它的逻辑b()不会被调用.想想它就像在mainloop()中插入一个().

考虑这个例子:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读