简体   繁体   English

运行两个异步功能而不会互相阻塞

[英]Run two async functions without blocking each other

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

The current output: 当前输出:

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

The desired output would be something like this: 所需的输出将是这样的:

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

I've tried some other stuff ( asyncio.wait , for example) but none worked as expected. 我尝试了其他一些东西(例如asyncio.wait ),但没有一个按预期工作。 Also the documentation it's not easy to understand when you're pretty new with Python asyncio . 另外,当您asyncio Python asyncio时,很难理解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 的Python 3.6.2

You need your asynchronous functions to yield the CPU while waiting, so that other asynchronous functions get a chance to run. 您需要异步函数来在等待时释放CPU,以便其他异步函数有运行的机会。 Yielding the CPU is done, using the await keyword. 使用await关键字完成CPU的生成。 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. 另外,您需要使用asyncio定义的sleep(...)函数作为正常时间asyncio time.sleep(...)不允许重新输入产生的函数。 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')

Thus, all you practically have to do, is replace time.sleep(...) with await asyncio.sleep(...) . 因此,你实际上需要做的,是取代time.sleep(...)await asyncio.sleep(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 异步功能意外地相互阻塞 - Async functions are unexpectedly blocking each other 是否可以同时运行两个函数? - Is it possible to run two functions concurrent to each other? Gevent:使用具有两个使用者的两个队列而不会互相阻塞 - Gevent: Using two queues with two consumers without blocking each other at the same time 如何使两个带有 TKinter 的测试按钮运行两个相互独立的功能? Python3 - How can I make two test buttons with TKinter run two functions independent of each other? Python3 有两个函数可以无休止地运行吗? - Is it acceptable to have two functions that run each endlessly? 在 Tornado 的阻塞上下文中调用异步函数 - Call async functions in blocking context in Tornado 一次运行两个阻止功能 - Running two blocking functions at once 使用多个功能互相作用而不连续重复 - Use multiple functions act on each other without repeating in succession 如何在 python 中编写两个相邻的函数? - How can I write two functions next to each other in python? 如何在另一个进程/线程中运行模块并使用它的功能而不阻塞主脚本 - How do I run a module in another process/thread and use it's functions without blocking main script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM