Make a function thread safe

邮差的信 提交于 2021-02-10 15:51:18

问题


I'm trying to understand why some functions fail with threading in python. For example, I'm trying to use VideoCapture to grab an image from a webcam. This example works fine:

from VideoCapture import Device

cam = Device()
cam.saveSnapshot('image.jpg')

But when I put it on a thread I get an error.

import threading
from VideoCapture import Device

def grab():
    cam = Device()
    cam.saveSnapshot('image.jpg')

thr = threading.Thread(target=grab)
thr.start()
thr.join()

File "C:\Program Files\Python36\lib\site-packages\VideoCapture__init__.py", line 60, in init self.dev = vidcap.new_Dev(devnum, showVideoWindow) vidcap.Error: Creation of the filter graph failed.

According to this reference, this function is not thread-safe. So is there any workaround to bypass similar issues like this? I tried to use threading.lock but got the same error. If I need to change the code, which part should I check?


回答1:


I couldn't find a direct way to fix it, but importing the module inside the thread fixed that, I'm not sure if this applies to other modules.

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()


来源:https://stackoverflow.com/questions/52287923/make-a-function-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!