You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中共享内存封装为类后无法正常工作的问题排查

问题:封装SharedMemory类后进程异常退出,错误码0xC000013A

我正在使用Python的multiprocessing.shared_memory模块在同一计算机的进程间快速传输图片。直接编写共享内存代码时一切正常,但封装为类后无法运行,报错:
Process finished with exit code -1073741510 (0xC000013A: interrupted by Ctrl+C)

可正常运行的代码:

import numpy as np
from multiprocessing import shared_memory
import cv2

w, h = 1920, 1080
shm = shared_memory.SharedMemory(create=True, name="SharedVideoBuffer", size=w*h*3)
im = np.ndarray((h, w, 3), dtype=np.uint8, buffer=shm.buf)

image = cv2.imread("19201080.jpg")

while True:
    im[:] = image

报错的封装代码:

import numpy as np
from multiprocessing import shared_memory
import cv2

w, h = 1920, 1080


class SharedMemImagePub:
    def __init__(self):
        shm = shared_memory.SharedMemory(create=True, name="SharedVideoBuffer", size=w * h * 3)
        self.im = np.ndarray((h, w, 3), dtype=np.uint8, buffer=shm.buf)

    def publish_image(self, cv_image):
        self.im[:] = cv_image


if __name__ == '__main__':
    shmem_image_pub = SharedMemImagePub()
    image = cv2.imread("19201080.jpg")
    while True:
        shmem_image_pub.publish_image(image)

问题原因

核心是SharedMemory对象的生命周期管理问题:

  • 非封装代码中,shm是全局变量,始终保持引用,不会被Python垃圾回收机制销毁,共享内存资源一直有效。
  • 封装后的代码里,__init__方法中的shm是局部变量,初始化完成后就失去了引用,Python的垃圾回收会自动关闭这个共享内存对象。后续操作self.im(依赖共享内存的buffer)时,由于底层资源已被释放,会触发进程异常退出,表现为类似Ctrl+C中断的错误码。

修复后的代码

将shm保存为类的实例属性,维持对SharedMemory对象的引用,避免被垃圾回收:

import numpy as np
from multiprocessing import shared_memory
import cv2

w, h = 1920, 1080


class SharedMemImagePub:
    def __init__(self):
        # 将shm保存为实例属性,维持引用
        self.shm = shared_memory.SharedMemory(create=True, name="SharedVideoBuffer", size=w * h * 3)
        self.im = np.ndarray((h, w, 3), dtype=np.uint8, buffer=self.shm.buf)

    def publish_image(self, cv_image):
        self.im[:] = cv_image
        
    def close(self):
        # 可选:添加关闭方法,退出时手动释放共享内存
        self.shm.close()
        self.shm.unlink()


if __name__ == '__main__':
    shmem_image_pub = SharedMemImagePub()
    image = cv2.imread("19201080.jpg")
    try:
        while True:
            shmem_image_pub.publish_image(image)
    except KeyboardInterrupt:
        # 捕获Ctrl+C,手动释放资源
        shmem_image_pub.close()

内容的提问来源于stack exchange,提问作者kevinlinxc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 00:53:10