AsyncIO part 2: Threads, green threads, coroutines and The Event Loop.

Taras Voinarovskyi
Taras Voinarovskyi

Member of aio-libs team

Threads

  • Minimum 1 MB per Thread (8MB default)
  • Context switching is expensive
  • Processing bound to 1 CPU
  • Other GIL related issues
  • etc.

Why can be bad in some cases:

Green threads

PyPy's continulet

greenlet

Stackless tasklet

coroutines

tasks

Green threads

Coroutines

PEP 492 -- Coroutines with async and await syntax

async def my_coroutine():
    res = await io_operation()

    async with my_async_context():
        print("In context")

    async for x in my_asyn_iter():
        print("Yielded", x)

        yield "We can even do async generators"        

Coroutines

import time


class Future:

    def __await__(self):
        sleep_time = 0
        while True:
            sleep_time = yield f"Sleeping for {sleep_time}s"
            time.sleep(sleep_time)


async def coro():
    await Future()

c = coro()

Coroutines

Questions?

Made with Slides.com