问题
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