写一个 trio 程序实现异步加载大数组并在后台线程执行 ufunc
解读
面试官真正想看的是三件事:
- 能不能把“耗时 IO”与“CPU 密集计算”拆成两条流水线,互不阻塞事件循环;
- 对 trio 的“协程 + 线程”混合模型是否熟悉,会不会用
trio.to_thread.run_sync把 GIL 受限的 NumPy ufunc 丢到真正的 OS 线程; - 资源与生命周期管理是否严谨——大数组动辄几 GB,必须边流式读取、边及时落盘或释放,防止把容器/笔记本直接打爆。
国内一线厂(阿里、头条、华为)的线上笔试机考环境默认装好 trio 与 NumPy,但内存上限通常只有 4~8 GB,如果候选人一次性 np.load 8 GB 文件再 np.exp 直接 OOM,会直接判 0 分。因此代码里必须体现“分块加载 + 后台线程池 + 结果异步回写”三板斧。
知识点
- trio 的 Nurseries 与结构化并发:所有子协程必须在 nursery 作用域内,异常自动冒泡;
trio.to_thread.run_sync的cancellable=True参数,允许 Ctrl-C 时把线程任务一并杀掉;- NumPy 的
np.lib.format.open_memmap实现真正的内存映射,不占用 Python 堆; - ufunc 的
dtype=与out=参数,可原地计算避免额外一次拷贝; - 国内云主机多为 x86_64,NUMA 节点 2~4,线程池大小取
min(32, CPU_COUNT*2)最稳; - 大文件分块策略:默认按“128 MiB / itemsize”行数切分,兼顾 L2 Cache 友好与内存占用;
- 异步文件接口
trio.open_file支持“直接落盘”或“管道给下游任务”,防止缓冲堆积。
答案
# filename: async_numpy_ufunc.py
import os, math, trio, numpy as np
from typing import Tuple
CHUNK_BYTES = 128 * 1024 * 1024 # 128 MiB
UFUNC = np.exp # 可替换成任意 ufunc
THREADS = min(32, (os.cpu_count() or 1) * 2)
async def load_chunk(file_path: str, offset: int, count: int) -> np.ndarray:
"""异步读取二进制块(trio 线程池负责系统调用,不阻塞事件循环)"""
dtype = np.dtype(np.float64)
itemsize = dtype.itemsize
with open(file_path, "rb") as f:
f.seek(offset * itemsize)
buf = await trio.to_thread.run_sync(f.read, count * itemsize,
cancellable=True)
return np.frombuffer(buf, dtype=dtype)
def cpu_bound_task(arr: np.ndarray) -> np.ndarray:
"""纯 NumPy 计算,GIL 内部释放,适合放到线程"""
out = np.empty_like(arr)
UFUNC(arr, out=out) # 原地 ufunc,无额外拷贝
return out
async def process_one_chunk(file_path: str, offset: int, count: int,
send_chan: trio.MemorySendChannel):
"""单块流水线:读 -> 计算 -> 异步发送结果"""
arr = await load_chunk(file_path, offset, count)
result = await trio.to_thread.run_sync(cpu_bound_task, arr,
limiter=trio.CapacityLimiter(THREADS))
await send_chan.send((offset, result)) # 顺序号保证下游能重组
async def write_result(file_path: str, recv_chan: trio.MemoryReceiveChannel,
total_items: int):
"""按 offset 顺序回写,防止随机磁盘 seek"""
dtype = np.dtype(np.float64)
itemsize = dtype.itemsize
async with await trio.open_file(file_path, "wb") as f:
# 预分配空洞文件,避免频繁扩展
await trio.to_thread.run_sync(f.truncate, total_items * itemsize)
async for offset, data in recv_chan:
pos = offset * itemsize
await f.seek(pos)
await f.write(data.tobytes())
async def main(in_file: str, out_file: str):
"""结构化并发:读侧 nursery 负责分块,写侧单任务顺序落盘"""
file_size = os.path.getsize(in_file)
dtype = np.dtype(np.float64)
total_items = file_size // dtype.itemsize
chunk_items = CHUNK_BYTES // dtype.itemsize
chunks = int(math.ceil(total_items / chunk_items))
async with trio.open_nursery() as nursery:
send_chan, recv_chan = trio.open_memory_channel(0)
# 写任务
nursery.start_soon(write_result, out_file, recv_chan, total_items)
# 读+计算任务
for i in range(chunks):
offset = i * chunk_items
count = min(chunk_items, total_items - offset)
nursery.start_soon(process_one_chunk, in_file, offset,
count, send_chan)
if __name__ == "__main__":
trio.run(main, "big.in.bin", "big.out.bin")
运行方式
# 生成测试文件
python -c "import numpy as np; np.random.rand(2_000_000_000).astype(np.float64).tofile('big.in.bin')"
# 执行
python async_numpy_ufunc.py
内存峰值 ≈ CHUNK_BYTES * 2(读 + 写双缓冲),远小于一次性加载;CPU 占用可打满所有物理核心,IO 与计算重叠,事件循环保持响应。
拓展思考
- 如果输入是
.npy格式而非裸二进制,可用np.lib.format.read_array的offset与count参数实现分块;但注意.npy头 128 字节需先解析,防止错位。 - 对于 GPU 场景(cuPy),可把
cpu_bound_task换成cupy.get_array_module(arr).exp(arr),再用trio.lowlevel.current_trio_token().run_sync_cancellable把 CUDA kernel 提交到另一个进程池,实现“CPU 读 -> GPU 算 -> CPU 写”三段流水线。 - 国内部分内网环境禁用
trio.to_thread的cancellable=True,此时可退而求其次用trio.run_sync_in_worker_thread并自行维护threading.Event做优雅退出。 - 若文件在阿里云 OSS/HDFS,可把
load_chunk换成trio.to_thread.run_sync(oss2.Bucket.get_object, Range=...),实现“边下载边计算”,节省本地磁盘占用。 - 真实业务里往往要对 ufunc 结果做压缩落盘(blosc/zstd),可在
write_result里引入numcodecs.Blosc,压缩率 3~5 倍,显著降低网络传输费用。