liveBook · Manning

Event loop

As explained in Building LLM Applications with DSPy

An event loop schedules and runs asynchronous tasks, switching between them when they complete or suspend.

An event loop runs tasks created from coroutines, executing one task at a time and switching when a task completes or pauses at an await point. asyncio.run() creates and starts the loop, which runs until its managed tasks finish. section 7.5.1

Listing 7.17 asyncio example
import asyncio
import time

async def func1():
    print("Start func1")
    await asyncio.sleep(5)
    print("End func1")
    return "func1 complete"

async def func2():
    print("Start func2")
    await asyncio.sleep(3)
    print("End func2")
    return "func2 complete"

async def main():
    start_time = time.time()
    co_routines = asyncio.gather(func1(), func2())
    a, b = await co_routines
    print(a, b)
    end_time = time.time()
    print("time", end_time-start_time)

asyncio.run(main())

Two coroutines pause for different durations; asyncio.gather() lets the event loop run them concurrently and collect their results. section 7.5.1

How Building LLM Applications with DSPy covers it

How deep it goes
Explains task switching at await points and that only one task executes at a time.
Examples
Demonstrates two sleeping coroutines run with asyncio.gather(), with their results and elapsed time printed.
What it assumes
Introduces async/await and coroutine tasks by comparing coroutines with sequential subroutines.
What you can do after
Apply via asyncio.run() to start an event loop and run coroutine tasks.
How it connects
Links event loops to coroutines, tasks, async/await, and asyncio.

Also explained in

Compare how 11 books explain event loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building LLM Applications with DSPy. The section links point to the parts of the book it draws on.