使函数线程安全 [英] Make a function thread safe
问题描述
我试图理解为什么某些函数在 python 中线程失败.例如,我正在尝试使用 VideoCapture
从网络摄像头抓取图像.这个例子工作正常:
from VideoCapture 导入设备凸轮 = 设备()cam.saveSnapshot('image.jpg')
但是当我把它放在一个线程上时,我得到了一个错误.
导入线程从 VideoCapture 导入设备定义抓取():凸轮 = 设备()cam.saveSnapshot('image.jpg')thr = threading.Thread(target=grab)thr.start()thr.join()
<块引用>
文件C:\ProgramFiles\Python36\lib\site-packages\VideoCapture__init__.py",第 60 行,在初始化self.dev = vidcap.new_Dev(devnum, showVideoWindow) vidcap.Error: 创建过滤器图失败.
根据这个参考,这个函数不是线程安全的.那么是否有任何解决方法可以绕过类似的问题?我尝试使用 threading.lock
但得到了同样的错误.如果我需要更改代码,我应该检查哪个部分?
我找不到直接的方法来修复它,但是在线程中导入模块修复了这个问题,我不确定这是否适用于其他模块.
导入线程定义抓取():从 VideoCapture 导入设备凸轮 = 设备()cam.saveSnapshot('image.jpg')德尔卡姆thr = threading.Thread(target=grab)thr.start()thr.join()
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?
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()
这篇关于使函数线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!