我有一个从相机中提取数据的图形应用程序。相机事件循环在对象中启动的线程中运行,我使用对象的 setter / getter 来获取数据并使用它。但有时应用程序会崩溃。我没有使用任何同步机制。
我有这个方法:
void MyClass::onNewColorSample(ColorNode node, ColorNode::NewSampleReceivedData data)
{
colorData = data;
}
我将其注册为外部库的回调:
g_cnode.newSampleReceivedEvent().connect(&onNewColorSample);
每次新帧从相机到达时调用该方法。
colorData
的 getter 是:
ColorNode::NewSampleReceivedData MyClass::getColorData()
{
return colorData;
}
然后我使用 pthread 运行以下命令:
void* MyClass::runThread(void* na)
{
g_context.run();
}
在某个时刻,我启动了线程:
pthread_create(&pthread, NULL, runThread, NULL);
然后 MyClass
类在线程中从摄像头获取数据。
库的运行方法文档说:
运行 DepthSense
事件循环。连接的事件处理程序在调用 run()
的线程中运行。
现在我使用 myClass
从相机获取数据,在另一个类中我有一个每 1/60 秒调用一次的方法:
static ColorNode::NewSampleReceivedData colorFrame;
depthFrame = dsCam.getDetphData();
...
有时应用程序会在 dsCam.getDepthData()
中崩溃。
我认为出现问题是因为当此方法返回时正在复制数据,并且在复制操作的中间我得到了新数据。
我使用线程是因为外部库不提供非阻塞机制来获取数据。它只是提供了一个基于事件的机制。
我担心如果我使用互斥锁定/解锁机制,我的 FPS 会下降,但我会尝试...请给我一些想法。
最佳答案
最后我使用 QMutex 解决了这个问题:
//RAII class to unlock after method return (when local var out of scope)
class AutoMutex {
public:
AutoMutex(QMutex* _mutex) {
_mutex->lock();
myMutex = _mutex;
}
~AutoMutex() {
myMutex->unlock();
}
private:
QMutex* myMutex;
};
然后我就使用了这个类,向它传递了一个指向互斥量的指针(互斥量是我类的一个成员):
ColorNode::NewSampleReceivedData MyClass::getColorData()
{
AutoMutex autoMut(&mutex); //mutex get locked
return colorData;
} //when method ends, autoMut is destroyed and mutex get unlocked
DepthNode::NewSampleReceivedData MyClass::getDetphData()
{
AutoMutex autoMut(&mutex);
return depthData;
}
关于c++ - 从相机中提取的异步数据会产生随机崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21892024/