Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Understanding Asynchronous Programming | Asynchronous Programming (asyncio)
Python Structural Programming

Understanding Asynchronous Programming

Svep för att visa menyn

Asynchronous programming is a way to write programs that can handle many tasks seemingly at the same time, without waiting for each task to finish before starting the next. This is especially useful for tasks that spend a lot of time waiting, such as reading files, making network requests, or interacting with databases. Instead of blocking your program while waiting for a task to complete, asynchronous programming allows your code to continue running other tasks.

At the heart of Python's asynchronous programming model is the event loop. The event loop is responsible for managing and scheduling tasks that are ready to run. It keeps track of all the tasks, checks which ones are waiting for something (like input or a timer), and runs the ones that are ready. This allows your program to make progress on multiple tasks without the need for multiple threads or processes.

A key building block of asynchronous programming in Python is the coroutine. Coroutines are special functions defined with async def. They can pause their execution at certain points using the await keyword, which tells the event loop to run other tasks while waiting for something to finish. When the awaited operation completes, the event loop resumes the coroutine right where it left off.

By using the event loop and coroutines, you can write code that is efficient and responsive, especially for I/O-bound programs. This approach is different from traditional threading or multiprocessing because it avoids the overhead of creating multiple threads or processes, and instead relies on the event loop to manage when each task runs.

import asyncio

async def greet_after_delay():
    print("Hello...")
    await asyncio.sleep(2)  # Pause here, let event loop run other tasks
    print("...world!")

# To actually run the coroutine, you need to use the event loop:
asyncio.run(greet_after_delay())

Output:

Hello...
...world!
question mark

Which of the following best describes the role of the event loop in Python's asynchronous programming?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 4. Kapitel 1
some-alt