[英]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.