Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Creating and Running Coroutines | Asynchronous Programming (asyncio)
Python Structural Programming

Creating and Running Coroutines

Stryg for at vise menuen

To start working with asynchronous programming in Python, you need to understand coroutines. A coroutine is a special function defined with async def. Coroutines allow you to pause and resume execution, making it possible to handle tasks like waiting for input/output operations - such as file reading, network requests, or database queries - without blocking the whole program. This means that while one task is waiting for data, other tasks can continue running, improving efficiency and responsiveness.

To run a coroutine, you use asyncio.run, which starts an event loop, runs your coroutine, and closes the loop when finished. This is the standard way to launch asynchronous code in modern Python.

Suppose you want to run more than one coroutine at the same time. You can use asyncio.gather to schedule them concurrently. This lets your program start multiple tasks and wait for all of them to finish, making better use of time especially when waiting for slow operations like I/O.

The following code demonstrates these concepts.

import asyncio

async def greet(name, delay):
    await asyncio.sleep(delay)
    print(f"Hello, {name}!")

async def main():
    # Schedule two coroutines to run concurrently
    await asyncio.gather(
        greet("Alice", 2),
        greet("Bob", 1)
    )

asyncio.run(main())

Expected result:

Hello, Bob!
Hello, Alice!

Bob's greeting appears first because it uses a shorter delay (1 second) than Alice's (2 seconds).

The greet coroutine is created with async def, allowing it to pause execution with await asyncio.sleep(delay) before printing a greeting. The main coroutine schedules two instances of greet - one for "Alice" with a 2-second delay, and one for "Bob" with a 1-second delay - using asyncio.gather. This means both greetings are handled concurrently, so the program does not wait for one to finish before starting the other. Finally, asyncio.run(main()) starts the event loop, runs the main coroutine, and ensures everything is cleaned up afterward. This approach lets you handle multiple tasks that involve waiting (like network requests or time delays) at the same time, making your program more efficient and responsive.

question mark

Which statement best describes how asyncio.gather schedules coroutines?

Vælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 4. Kapitel 2

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 4. Kapitel 2
some-alt