第一章:异步编程概述¶
同步 vs 异步¶
同步执行¶
import time
def task1():
time.sleep(1)
return "task1"
def task2():
time.sleep(1)
return "task2"
# 顺序执行,总耗时 2 秒
result1 = task1()
result2 = task2()
异步执行¶
import asyncio
async def task1():
await asyncio.sleep(1)
return "task1"
async def task2():
await asyncio.sleep(1)
return "task2"
# 并发执行,总耗时 1 秒
async def main():
results = await asyncio.gather(task1(), task2())
print(results)
asyncio.run(main())
为什么需要异步?¶
| 场景 | 同步 | 异步 |
|---|---|---|
| CPU 密集 | ✅ | ❌ |
| I/O 密集 | ❌ | ✅ |
| 高并发 | ❌ | ✅ |
| 网络请求 | ❌ | ✅ |
asyncio 基础¶
协程定义¶
import asyncio
# 方式1:async def
async def my_coroutine():
await asyncio.sleep(1)
return "done"
# 方式2:@asyncio.coroutine(已弃用)
@asyncio.coroutine
def old_style():
yield from asyncio.sleep(1)
运行协程¶
# 方式1:asyncio.run()
asyncio.run(my_coroutine())
# 方式2:事件循环
loop = asyncio.get_event_loop()
loop.run_until_complete(my_coroutine())
await 关键字¶
async def fetch_data():
await asyncio.sleep(1) # 等待异步操作
return "data"
async def process():
data = await fetch_data() # 等待结果
print(data)
并发执行¶
gather¶
async def main():
# 并发执行多个协程
results = await asyncio.gather(
task1(),
task2(),
task3()
)
print(results)
create_task¶
async def main():
# 创建任务
task = asyncio.create_task(task1())
# 做其他事情
print("doing other things")
# 等待任务完成
result = await task
print(result)
wait¶
async def main():
# 等待所有完成
done, pending = await asyncio.wait([
task1(),
task2(),
task3()
])
# 等待第一个完成
done, pending = await asyncio.wait([
task1(),
task2()
], return_when=asyncio.FIRST_COMPLETED)
超时处理¶
async def main():
try:
result = await asyncio.wait_for(
slow_task(),
timeout=5.0
)
except asyncio.TimeoutError:
print("任务超时")
小结¶
本章学习了:
- ✅ 同步 vs 异步
- ✅ 异步应用场景
- ✅ asyncio 基础
- ✅ 并发执行
- ✅ 超时处理
下一章¶
第二章:asyncio 详解 - 深入学习 asyncio。