
asyncio.run() 会阻塞主线程直至所有协程任务完成,因此后续同步代码不会“并发执行”;异步本身不创建新线程,所有协程共享主线程和 GIL,真正的并发需结合 threading 或 ThreadPoolExecutor 实现跨线程调度。
`asyncio.run()` 会阻塞主线程直至所有协程任务完成,因此后续同步代码不会“并发执行”;异步本身不创建新线程,所有协程共享主线程和 gil,真正的并发需结合 `threading` 或 `threadpoolexecutor` 实现跨线程调度。
在 Python 中,async/await 构建的是单线程协作式并发(cooperative concurrency),而非多线程并行。事件循环(Event Loop)始终运行在主线程中,通过挂起(await)和恢复协程的方式,在多个异步任务间快速切换——这本质上是时间片轮转式的协作调度,不涉及线程创建,也不绕过 GIL。
因此,原始代码中 asyncio.run(main()) 会一直阻塞主线程,直到 fetcher() 和 monitor() 这两个无限循环协程被显式取消或程序终止。由于二者均无退出条件,asyncio.run() 永远不会返回,自然也就无法执行 print("Rest of the method is executing....") ——这并非“并发未生效”,而是语义上的阻塞行为:asyncio.run() 的设计目标就是作为异步程序的主入口,它必须等待所有任务结束才退出。
✅ 正确实现“后台异步任务 + 主线程继续执行”的方式
若希望启动异步任务后立即返回主线程执行其他逻辑(如 UI 响应、日志输出或同步初始化),必须将事件循环置于独立线程中运行。以下是两种推荐实践:
方式一:使用 threading.Thread 启动事件循环
import asyncio
import threading
from queue import Queue
import time
q = Queue()
async def get_some_values_from_io():
print("Getsome value Executing...")
await asyncio.sleep(3)
return [100, 200]
async def fetcher():
while True:
print("Fetcher Executing...")
io_vals = await get_some_values_from_io()
for val in io_vals:
q.put(val)
async def monitor():
while True:
print("Monitor Executing... (queue size:", q.qsize(), ")")
await asyncio.sleep(3)
async def parallel():
await asyncio.gather(monitor(), fetcher())
# 在子线程中运行异步主逻辑
def run_async_in_thread():
asyncio.run(parallel())
thread = threading.Thread(target=run_async_in_thread, daemon=True) # daemon=True 避免阻塞进程退出
thread.start()
print("Rest of the method is executing....")
# 主线程可自由执行其他工作(如定时检查、用户输入等)
for i in range(5):
time.sleep(2)
print(f"[Main thread] Still alive, iteration {i+1}")
⚠️ 注意事项:
- 必须使用 daemon=True,否则主线程退出时子线程会阻止程序终止;
- 不要在非主线程中调用 asyncio.run() 以外的事件循环操作(如 asyncio.get_event_loop()),推荐始终用 asyncio.run() 封装入口;
- 跨线程通信建议使用线程安全的 queue.Queue,避免直接共享列表等非线程安全对象。
方式二:使用 concurrent.futures.ThreadPoolExecutor(更简洁可控)
from concurrent.futures import ThreadPoolExecutor
import asyncio
import time
async def get_some_values_from_io():
print("Getsome value Executing...")
await asyncio.sleep(3)
return [100, 200]
async def fetcher():
vals = []
while len(vals) <h3>? 关于 GIL 与 run_in_executor 的常见误解澄清</h3>
- ✅ GIL 依然存在:asyncio.to_thread() 或 loop.run_in_executor() 确实会将任务提交至线程池执行,从而绕过事件循环限制,但该线程仍受 GIL 约束——对 CPU 密集型任务提升有限;真正受益的是 I/O 密集型或需调用阻塞库(如 requests, sqlite3)的场景。
- ✅ 事件循环 ≠ 多线程:事件循环本身是单线程调度器,run_in_executor 是其提供的“桥梁”,用于桥接同步阻塞调用,而非改变异步模型的本质。
- ✅ 推荐组合模式:I/O 密集型逻辑用 async/await;需调用阻塞同步库时,用 await loop.run_in_executor(None, blocking_func);需长期后台服务且不依赖事件循环时,用 threading + asyncio.run()。
掌握这一分层逻辑,才能在高并发服务、爬虫、实时监控等场景中,精准选择 async、threading 与 multiprocessing 的适用边界。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











