> ## Content Index
> Fetch the complete content index at: https://yinguobing.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Possible Leak in OpenCV Threaded VideoCapture
- URL: https://yinguobing.com/blog/possible-leak-in-opencv-threaded-videocapture/
- Published: 2018-12-20T09:06:36.000Z
- Updated: 2022-05-29T08:51:14.000Z
- Description: 在OpenCV中频繁开启销毁新线程并读取视频可能存在内存泄露的问题。
- Author: 尹国冰
- Tags: 图像处理, OpenCV

在OpenCV中频繁开启销毁新线程并读取视频可能存在内存泄露的问题。最小代码如下。

```
#include <chrono>
#include <fstream>
#include <iostream>
#include <opencv2/highgui.hpp>
#include <string.h>
#include <thread>

using namespace std;

void open_video(string const& video_url)
{
    cv::VideoCapture cap(video_url);
    cv::Mat frame;
    cap.read(frame);
    cap.release();
    cout << "Video opened!" << endl;
}

int main(int argc, char** argv)
{
    // Get args form input.
    if (argc < 3) {
        cout << "Usage: " << argv[0]
             << " video_file loop_times" << endl;
        return -1;
    }

    string video_file = argv[1];
    int loop_times = atoi(argv[2]);

    // Loop through all the video files.
    for (int i = 0; i < loop_times; i++) {
        cout << "LOOP " << i << endl;

        thread parse_video(open_video, ref(video_file));
        parse_video.detach();

        // sleep for a while, waitting for the thread.
        this_thread::sleep_for(chrono::milliseconds(100));
    }
    return 0;
}
```

使用memory\_profile记录内存的使用情况如下图所示。

2019-03-20更新：官方已经确认了leak的存在，issue地址：[https://github.com/opencv/opencv/issues/13255](https://github.com/opencv/opencv/issues/13255?ref=yinguobing.com)