How to implement a circular buffer of cv::Mat objects (OpenCV)?
-
13-11-2019 - |
Question
I'm trying to implement a circular buffer for my program. The buffer is used to share data between two threads as shown below. I use OpenCV to grab video frames from camera (Thread 1). Then I would like to store this data in a circular buffer, so that Thread 2 can get the data from the buffer.
How can I implement a circular buffer for cv::Mat objects in c++? I know how to create circular buffer for standard c++ objects (like integer or char) but I can't make it work with objects of type cv::Mat. Any suggestions?
Solution
Solved, see Thread safe implementation of circular buffer
OTHER TIPS
Whats wrong with just a vector and an index to the next slot to write to and the next one to process?
All you have to handle is the wrap around when you get to the end, and if you use a power of 2 in the vector size you can use a simple mask for that.
A circular buffer is thread-safe when only the writing thread updates the end
pointer and only the reading thread updates the start
pointer, and accesses to those pointers are atomic. You have a spot in cbWrite
that updates start
which will lead to a race condition.