ทบทวน Async/Await ใน Python
ทบทวนแนวคิดหลักของการเขียนโปรแกรมแบบอะซิงโครนัสใน Python ซึ่งรวมถึงลูปเหตุการณ์และโครูทีน
ทบทวน Async/Await ใน Python เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Intro to Asynchronous Python
Welcome to the world of asynchronous programming in Python! This allows your programs to do multiple things without waiting for each task to finish before starting the next.
It's super useful for tasks that involve waiting, like network requests or reading/writing files, where your program would otherwise just sit idle.
Sync vs. Async: The Wait Game
Imagine cooking dinner:
- Synchronous: You chop vegetables, then wait for them to cook, then wash dishes. Only one task happens at a time.
- Asynchronous: You chop vegetables, put them on the stove, and while they're cooking (waiting), you start washing dishes. You're doing multiple things 'concurrently' by switching tasks when one is waiting.
Asynchronous programming helps your program stay busy instead of waiting!
The `async` Keyword: Coroutines
In Python, we use the async keyword to define a special type of function called a coroutine. A coroutine is a function that can be paused and resumed.
It doesn't run immediately when called; instead, it returns a 'coroutine object' that needs to be scheduled by an event loop to run.
import asyncio
async def hello_world():
print("Hello, async world!")
# Calling it directly doesn't run it!
# It returns a coroutine object.
coro_obj = hello_world()
print(f"Type of coro_obj: {type(coro_obj)}")
# To actually run it, you need an event loop.
# We'll see how in a moment!
`await`: Pausing Execution
The await keyword is used inside an async def function (a coroutine) to pause its execution until another awaitable (like another coroutine or a Future) completes.
When a coroutine awaits something, it temporarily gives control back to the event loop, allowing other tasks to run. This is key to non-blocking behavior.
import asyncio
async def cook_rice():
print("Starting to cook rice...")
await asyncio.sleep(2) # Simulate 2 seconds of cooking
print("Rice is cooked!")
async def chop_veg():
print("Chopping vegetables...")
await asyncio.sleep(1) # Simulate 1 second of chopping
print("Vegetables chopped!")
async def main_meal():
await chop_veg() # Wait for chopping to finish
await cook_rice() # Then wait for rice to cook
print("Dinner is ready!")
# This will run sequentially for now.
# We'll make it concurrent soon!
asyncio.run(main_meal())
The Event Loop: The Orchestrator
Think of the event loop as the conductor of an orchestra. It's responsible for:
- Scheduling when coroutines run.
- Handling I/O events (like network data arriving).
- Switching between tasks when one is waiting (e.g., due to
await).
Python's asyncio module provides the infrastructure for the event loop.
Running Async Code with `asyncio.run()`
To execute an asynchronous program, you typically use asyncio.run(). This function:
- Gets an event loop for the current thread.
- Runs the provided coroutine until it completes.
- Manages the event loop's lifecycle.
It's the simplest way to start your top-level async function.
import asyncio
async def say_hello():
print("Hello from coroutine!")
await asyncio.sleep(0.5) # Wait for 0.5 seconds
print("Goodbye from coroutine!")
async def main():
print("Starting async program...")
await say_hello()
print("Async program finished.")
# This is the entry point for your async application
asyncio.run(main())
Simulating Non-Blocking Operations
asyncio.sleep() is an 'awaitable' that pauses the current coroutine for a given time. Crucially, it does NOT block the entire program. While one coroutine is sleeping, the event loop can switch to and run other coroutines.
This is how asynchronous programming achieves concurrency without needing multiple threads.
import asyncio
import time
async def task_one():
print(f"Task One started at {time.strftime('%X')}")
await asyncio.sleep(2)
print(f"Task One finished at {time.strftime('%X')}")
async def task_two():
print(f"Task Two started at {time.strftime('%X')}")
await asyncio.sleep(1)
print(f"Task Two finished at {time.strftime('%X')}")
async def main():
start_time = time.monotonic()
await task_one()
await task_two()
end_time = time.monotonic()
print(f"Total time: {end_time - start_time:.2f} seconds")
asyncio.run(main())
Concurrent Execution with `asyncio.gather`
To truly run multiple coroutines concurrently (meaning they can interleave their execution when one awaits), we use asyncio.gather().
asyncio.gather() takes multiple awaitables and schedules them to run 'in parallel' on the event loop, waiting for all of them to complete.
import asyncio
import time
async def fetch_data(delay, name):
print(f"Fetching {name} data... (starts at {time.strftime('%X')})")
await asyncio.sleep(delay) # Simulate network request
print(f"Finished {name} data. (ends at {time.strftime('%X')})")
return f"Data from {name}"
async def main():
start_time = time.monotonic()
# Run fetch_data for 'users' and 'products' concurrently
user_data, product_data = await asyncio.gather(
fetch_data(2, "users"),
fetch_data(1, "products")
)
end_time = time.monotonic()
print(f"\nReceived: {user_data}, {product_data}")
print(f"Total time: {end_time - start_time:.2f} seconds")
asyncio.run(main())
Async/Await Concepts Check
Which of the following statements about Python's async and await keywords are TRUE?
Refresher Recap & Next Steps
Fantastic! You've refreshed your understanding of Python's asynchronous fundamentals:
- Asynchronous programming helps manage I/O-bound tasks efficiently.
async defdefines coroutines, functions that can be paused.awaitpauses a coroutine, yielding control to the event loop.- The event loop orchestrates coroutine execution.
asyncio.run()starts your async application.asyncio.gather()allows running multiple coroutines concurrently.
Next, we'll see how FastAPI leverages these powerful concepts to build high-performance web APIs!
คำถามที่พบบ่อย
บทเรียน “ทบทวน Async/Await ใน Python” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ทบทวน Async/Await ใน Python” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ทบทวน Async/Await ใน Python”
ทบทวนแนวคิดหลักของการเขียนโปรแกรมแบบอะซิงโครนัสใน Python ซึ่งรวมถึงลูปเหตุการณ์และโครูทีน คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “ทบทวน Async/Await ใน Python” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ทบทวน Async/Await ใน Python
- FastAPI และการทำงานแบบอะซิงโครนัส
- การทำงานเบื้องหลัง
- WebSockets เพื่อการสื่อสารแบบเรียลไทม์