运行两个异步功能而不会互相阻塞 [英] Run two async functions without blocking each other

查看:88
本文介绍了运行两个异步功能而不会互相阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步功能,我想并行"运行另一个.但是我需要在第一个功能内的某个时刻这样做.

I have an async function and I want to run another one "in parallel". But I need to do it at a certain moment inside that first function.

我已经看到了很多示例,但是它们都同时启动了两个功能,而那不是我想要的.

I've seen a lot of examples, but all of them were launching two functions at the same time, and that's not what I want.

我创建了这个简单的示例来说明我想要实现的目标(以及我尝试过的目标):

I've created this simple example to illustrate what I want to achieve (and what I've tried):

import asyncio
import time

async def print_letters():
    for letter in ['A', 'B', 'C', 'D']:
        print(letter)
        time.sleep(1)

async def print_numbers(loop):
    for number in range(1, 7):
        if(number == 3):
            # same result with create_task
            # loop.create_task(print_letters())
            asyncio.ensure_future(print_letters())
        print(number)
        time.sleep(1)

loop = asyncio.get_event_loop()
loop.run_until_complete(print_numbers(loop))
print('End')

当前输出:

1、2、3、4、5、6,A,B,C,D,结束

1, 2, 3, 4, 5, 6, A, B, C, D, End

所需的输出将是这样的:

The desired output would be something like this:

1、2、3,A,4,B,5,C,6 D,结束

1, 2, 3, A, 4, B, 5, C, 6 D, End

我尝试了其他一些操作(例如, asyncio.wait ),但没有一个能按预期工作.另外,当您使用Python asyncio 相当陌生时,很难理解该文档.

I've tried some other stuff (asyncio.wait, for example) but none worked as expected. Also the documentation it's not easy to understand when you're pretty new with Python asyncio.

如果问题不清楚或缺少某些内容,请告诉我,以便我进行编辑.感谢您的帮助.

If the question is unclear or there's something missing, let me know so I can edit it. I appreciate any kind of help.

Python 3.6.2

推荐答案

您需要异步函数来在等待时释放CPU,以便其他异步函数有运行的机会.使用 await 关键字完成CPU的产生.另外,您需要像正常的 time.sleep(...)一样使用在 asyncio 中定义的 sleep(...)功能.不允许重新输入产生的功能.总而言之,这要求您的程序是

You need your asynchronous functions to yield the CPU while waiting, so that other asynchronous functions get a chance to run. Yielding the CPU is done, using the await keyword. In addition you need to use the sleep(...) funtion defined in asyncio as the normal time.sleep(...) does not allow re-entry into the yielded funtion. All-in-all, this requires your program to be

import asyncio

async def print_letters():
    for letter in ['A', 'B', 'C', 'D']:
        print(letter)
        await asyncio.sleep(1)

async def print_numbers(loop):
    for number in range(1, 7):
        if(number == 3):
            # same result with create_task
            # loop.create_task(print_letters())
            asyncio.ensure_future(print_letters())
        print(number)
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()
loop.run_until_complete(print_numbers(loop))
print('End')

因此,您实际上要做的就是将 time.sleep(...)替换为 await asyncio.sleep(...).

Thus, all you practically have to do, is replace time.sleep(...) with await asyncio.sleep(...).

这篇关于运行两个异步功能而不会互相阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆