Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära What is Asynchronous Programming? | Getting Started with Asyncio
/
Python Asyncio Basics

bookWhat is Asynchronous Programming?

Svep för att visa menyn

When you write Python code, you usually run it in a synchronous way: each line finishes before the next one starts. This is called synchronous programming. For example, if your code needs to fetch data from the internet or wait for a file to load, the entire program stops and waits until that operation is finished. This can make your programs slow or unresponsive, especially if you have to wait for several slow tasks.

Asynchronous programming is different. Instead of waiting for each task to finish before starting the next, your code can start a task, move on to something else, and come back to the first task when it's ready. This is especially useful for operations that spend a lot of time waiting, like network requests, file input/output, or timers. In Python, the asyncio library lets you write asynchronous code that can handle many waiting tasks at once, making your programs more efficient and responsive.

123456789101112131415161718
import time import asyncio def sync_wait(): print("Synchronous: Waiting for 2 seconds...") time.sleep(2) print("Synchronous: Done!") async def async_wait(): print("Asynchronous: Waiting for 2 seconds...") await asyncio.sleep(2) print("Asynchronous: Done!") # Run the synchronous version sync_wait() # Run the asynchronous version asyncio.run(async_wait())
copy

In the code above, the sync_wait function uses time.sleep(2) to pause for two seconds. During this pause, nothing else can happen in your program. The async_wait function, on the other hand, uses await asyncio.sleep(2), which allows other tasks to run while waiting. This is a key difference between synchronous and asynchronous programming.

question mark

What is the main advantage of asynchronous programming in Python?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. 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 1. Kapitel 1
some-alt