垫队列中的访问冲突

Access violation in Mat queue

我正在编写一个 producer/consumer 从外部库接收帧日期的代码。

每一帧都在回调函数中从在并行线程中运行的外部库中读取,并被推入 Mat 队列。我创建了另一个在不同线程中运行的函数,该线程读取并弹出每一帧。

问题是当我尝试从队列中读取帧数据时出现“访问冲突读取位置”。

我正在全局声明这些变量:

queue<Mat> matQ;
OnFrameDataReceivedCB videoCB;
OnDeviceConnectStatusCB connectCB;
guide_usb_video_mode_e videoMode;
int width = 640;
int height = 512;
std::mutex mu;

每帧数据推送的回调函数代码如下:

void OnVideoCallBack(const guide_usb_frame_data_t data) //callback function
{
    if (data.frame_rgb_data_length > 0)
    {
        // Send the displayed data directly
        unsigned char* rgbData;
        Mat frame;
        Size size = Size(width, height);
        rgbData = data.frame_rgb_data;
        frame = Mat(size, CV_8UC3, rgbData, Mat::AUTO_STEP);


        if (mu.try_lock())
        {
            printf("producing...\n");
            matQ.push(frame);
            printf("free producing\n");
            mu.unlock();
        }

    }
}

这是从队列中读取的函数:

void OnHandleVideoData()
{
    while (true)
    {
        try
        {
            if (matQ.size() <= 0)
            {
                chrono::milliseconds duration(200);
                this_thread::sleep_for(duration);
                continue;
            }


            if (mu.try_lock())
            {
                if (matQ.size() > 0)
                {
                    printf("consuming...\n");
                    Size size = Size(width, height);
                    Mat frame = Mat(size, CV_8UC3);
                    frame = matQ.front().clone();
                    matQ.pop();
                    imwrite("frame.jpg", frame); //the access violation exception is thrown on this line
                    printf("free consuming\n");
                    mu.unlock();
                }
            }
            
        }
        catch (...)
        {
            
        }
    }

}

我也尝试将 unsigned char* rgbData 数组而不是 Mat 放入队列中,但我得到了同样的错误。

我错过了什么?

您应该尝试在收到帧时立即克隆它:

frame = Mat(size, CV_8UC3, rgbData, Mat::AUTO_STEP).clone();

而不是那里:

frame = matQ.front()/*.clone()*/;