Nâng CaoPython iconPython

`asyncio.gather` vs `asyncio.TaskGroup` — khác nhau gì?

asyncio.gather (Python 3.4+): chạy song song, trả về list kết quả. asyncio.TaskGroup (Python 3.11+) — recommended cách mới: nếu một task fail, các tasks còn lại bị cancel tự động.

python
# gather — return_exceptions để không propagate lỗi
results = await asyncio.gather(
    task1(), task2(), task3(),
    return_exceptions=True
)

# TaskGroup — structured concurrency (recommended 3.11+)
async with asyncio.TaskGroup() as tg:
    t1 = tg.create_task(task1())
    t2 = tg.create_task(task2())
# Tất cả tasks xong khi thoát context
# Nếu 1 task raise exception → cancel tasks còn lại
print(t1.result(), t2.result())

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python