综合开发

Two independent asynchronous loops at Python

微信扫一扫,分享到朋友圈

Two independent asynchronous loops at Python

What would be a good approach to execute two asynchronous loops running in parallel in Python, using async/await
?

I’ve thought about something like the code below, but can’t wrap my head around how to use async
/ await
/ EventLoop
in this particular case.

import asyncio

my_list = []

def notify():
    length = len(my_list)
    print("List has changed!", length)

async def append_task():
    while True:
        time.sleep(1)
        await my_list.append(random.random())
        notify()

async def pop_task():
    while True:
        time.sleep(1.8)
        await my_list.pop()
        notify()

loop = asyncio.get_event_loop()
loop.create_task(append_task())
loop.create_task(pop_task())
loop.run_forever()

Expected output:

$ python prog.py
List has changed! 1 # after 1sec
List has changed! 0 # after 1.8sec
List has changed! 1 # after 2sec
List has changed! 2 # after 3sec
List has changed! 1 # after 3.6sec
List has changed! 2 # after 4sec
List has changed! 3 # after 5sec
List has changed! 2 # after 5.4sec

this works fine:

note: you wanted to await fast non-io bound operations ( list.append
and list.pop
that are not even coroutines); what you can do is await

asyncio.sleep(...)

(which is a coroutine and yield control back to the caller):

import asyncio
import random

my_list = []

def notify():
    length = len(my_list)
    print("List has changed!", length)

async def append_task():
    while True:
        await asyncio.sleep(1)
        my_list.append(random.random())
        notify()

async def pop_task():
    while True:
        await asyncio.sleep(1.8)
        my_list.pop()
        notify()

loop = asyncio.get_event_loop()
cors = asyncio.wait([append_task(), pop_task()])
loop.run_until_complete(cors)

time.sleep
itself is blocking and does not play nicely with await
.

Google releases source code for Google I/O 2019 for Android

上一篇

OpenCV and Node.js - Image processing

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

Two independent asynchronous loops at Python

长按储存图像,分享给朋友