异步化技巧:(本质上还是多线程,并发效率会比较低,不建议)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import asyncio
import time

def blocking_task(name, duration):
"""同步阻塞任务"""
print(f"{time.time():.1f}: {name} 开始")
time.sleep(duration)
print(f"{time.time():.1f}: {name} 完成")
return f"{name} 结果"

# 方法1:直接在async函数中调用同步函数(会阻塞)
async def async_but_blocking(name, duration):
"""❌ 虽然是async函数,但内部调用阻塞操作"""
return blocking_task(name, duration)

# 方法2:在async函数中使用线程池(不会阻塞)
async def async_with_thread_pool(name, duration):
"""✅ async函数,使用线程池执行阻塞操作"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, blocking_task, name, duration)

async def compare_async_methods():
print("=" * 50)
print("方法1:async函数直接调用阻塞操作")
start1 = time.time()

# 虽然用了 asyncio.gather,但因为内部是阻塞的,所以还是串行执行
results1 = await asyncio.gather(
async_but_blocking("阻塞-任务1", 2),
async_but_blocking("阻塞-任务2", 2),
async_but_blocking("阻塞-任务3", 2)
)

print(f"方法1总耗时: {time.time() - start1:.1f}秒")
print(f"结果: {results1}\n")

print("=" * 50)
print("方法2:async函数使用线程池")
start2 = time.time()

# 真正的并发执行
results2 = await asyncio.gather(
async_with_thread_pool("线程池-任务1", 2),
async_with_thread_pool("线程池-任务2", 2),
async_with_thread_pool("线程池-任务3", 2)
)

print(f"方法2总耗时: {time.time() - start2:.1f}秒")
print(f"结果: {results2}")

asyncio.run(compare_async_methods())