代码之家  ›  专栏  ›  技术社区  ›  Masoud Rahimi Chris

使函数线程安全

  •  1
  • Masoud Rahimi Chris  · 技术社区  · 6 年前

    例如,我尝试使用 VideoCapture

    from VideoCapture import Device
    
    cam = Device()
    cam.saveSnapshot('image.jpg')
    

    import threading
    from VideoCapture import Device
    
    def grab():
        cam = Device()
        cam.saveSnapshot('image.jpg')
    
    thr = threading.Thread(target=grab)
    thr.start()
    thr.join()
    

    文件“C:\程序 在里面 初始化 自我开发= vidcap.new\u开发(设备,showVideoWindow)vidcap.错误:创建筛选器图形失败。

    this reference ,此函数不是线程安全的。那么,有什么解决方法可以绕过类似的问题吗?我试着用 threading.lock

    1 回复  |  直到 6 年前
        1
  •  0
  •   Masoud Rahimi Chris    6 年前

    我找不到直接的方法来修复它,但是在线程中导入模块解决了这个问题,我不确定这是否适用于其他模块。

    import threading
    
    def grab():
        from VideoCapture import Device
        cam = Device()
        cam.saveSnapshot('image.jpg')
        del cam
    thr = threading.Thread(target=grab)
    thr.start()
    thr.join()