【问题标题】:Asynchronous data pulling from a camera produces random crash从相机中提取的异步数据会产生随机崩溃
【发布时间】:2014-02-19 20:44:46
【问题描述】:

我有一个从相机中提取数据的图形应用程序。相机事件循环在对象中启动的线程中运行,我使用对象的 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 会下降,但我会尝试...请给我一些想法。

【问题讨论】:

    标签: c++ multithreading asynchronous


    【解决方案1】:

    最后我用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多