Reputation: 5978
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 int
or char
) but I can't make it work with objects of type cv::Mat
.
Any suggestions?
Upvotes: 5
Views: 7274
Reputation: 308206
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.
Upvotes: 1
Reputation: 96109
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.
Upvotes: 3