async နှင့် await ဖြင့် Concurrency

3.15.2

Coroutine သုံးပါ။ သီးခြား I/O အလုပ်တွေ တစ်ပြိုင်နက် စီမံပြီး cancellation ကို ကိုင်တွယ်ပါ။

ဒီစာမျက်နှာမှာ

Coroutines နှင့် Event Loop

async def function ကို ခေါ်ရင် coroutine object ရပါတယ်။ await က awaitable ကို စောင့်ပြီး လက်ရှိ task ကို ခဏရပ်လို့ တခြား task တွေ run နိုင်ပါတယ်။ ပုံမှန် script စဖို့ asyncio.run() သုံးပါ။ Event loop ဖွင့်ထားတဲ့ notebook မှာ ပုံမှန်အားဖြင့် top-level await သုံးနိုင်ပါတယ်။

import asyncio

async def main():
    await asyncio.sleep(0)
    print("Ready")

asyncio.run(main())
နမူနာ ရလဒ်
Ready

သီးခြား Task တွေ အတူ Run ခြင်း

TaskGroup က coroutine တွေ schedule လုပ်ပြီး block မထွက်ခင် group အားလုံးကို စောင့်ပါတယ်။ Task တစ်ခု fail ရင် ပုံမှန်အားဖြင့် ကျန် task တွေ cancel လုပ်ပါတယ်။ Loop ထဲ asynchronous I/O သုံးပြီး CPU အများကြီးစားတာနဲ့ blocking အလုပ်တွေကို သီးခြားလုပ်ပါ။ Cleanup အတွက် try/finally သုံးပြီး cancellation ဆက်သွားခွင့်ပေးပါ။

import asyncio

async def read_source(name):
    await asyncio.sleep(0.01)
    return name

async def main():
    async with asyncio.TaskGroup() as group:
        sales = group.create_task(read_source("sales"))
        inventory = group.create_task(read_source("inventory"))
    print(sales.result(), inventory.result())

asyncio.run(main())
နမူနာ ရလဒ်
sales inventory

တရားဝင် ကိုးကားချက်များ