7,651
社区成员
发帖
与我相关
我的任务
分享hon 调用 QNN 做批量图像推理,频繁出现 GIL 锁阻塞导致推理吞吐量上不去,如何解决?
阻塞原因
Python 全局 GIL 锁使得同一时刻仅有一个线程执行 CPU 运算,即便 NPU 空闲,多线程推理预处理阶段也会被 GIL 限制,无法并发送帧至 NPU。
解决方案
将图像预处理逻辑剥离 Python,封装为独立 C++ 动态库,脱离 GIL 运行;
使用多进程架构替代多线程,每个进程单独持有一套 QNN 模型上下文,进程间通过队列传递图像路径;
NPU 设置批量推理 batch 参数,单次送入多张图片推理,减少推理调用次数。
多进程调度 Python 示例
python
运行
from multiprocessing import Pool, Queue
def infer_subprocess(img_queue):
# 子进程单独初始化QNN模型,互不干扰
from qnn_wrapper import QnnModel
model = QnnModel("batch_model.dlc")
while True:
img_path = img_queue.get()
if img_path is None: break
img = cv2.imread(img_path)
res = model.infer(img)
if name == "main":
task_queue = Queue()
process_num = 2
pool = Pool(processes=process_num, initializer=infer_subprocess, initargs=(task_queue,))
# 投递图片任务
for path in img_list:
task_queue.put(path)
for _ in range(process_num):
task_queue.put(None)
pool.close()
pool.join()
优化效果
规避 GIL 限制后,骁龙 AI PC 批量图片推理吞吐量可提升 2 倍以上。