5

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.

enter image description here

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?

7
  • 2
    What difficulty are you having with the cv::Mat portion of the problem? How does that data type change the task of writing a circular buffer? Commented Feb 27, 2012 at 22:03
  • @RobKennedy I included the code that I'm having problems with. I used en.wikipedia.org/wiki/Circular_buffer as example and modified it to store data of cv::Mat type (instead of type 'int') but now the code throws a run-time error. Thank you. Commented Feb 27, 2012 at 22:55
  • 1
    The circular buffer code itself works fine for me (MSVC 2010 Ultimate SP1), which means your crash is cause by something OpenCV related, which you would probably be best off using a debugger to find. Commented Feb 27, 2012 at 23:03
  • Is this the actual code that's crashing? I don't see threads here. Commented Feb 27, 2012 at 23:12
  • In cbWrite shouldn't the check be for cb->end==cb->size (to reset cb->end = 0 to avoid buffer overruns? I realize this probably isn't what is leading to the crash but it still looks dangerous. Commented Feb 27, 2012 at 23:13

3 Answers 3

5

Solved, see Thread safe implementation of circular buffer

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

Thanks. I will look into this tomorrow.
@Alex, using a vector will certainly simplify the code but I don't think it will fix your error. Be certain to size the vector to the capacity of the circular buffer before trying to use it.
1

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.

1 Comment

The sample code (that's crashing) does not have threads yet. Thanks for the tip though; implementing threads will be my next step.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.