We try to develop a realtime application. In this program 4 cameras send 100 times a second there image array to a method. In this method I have to make copy of each array. (Used for ImageProcessing in other thread).
I would like to store the last 100 images of each camera in a list.
The problem is: How to prealloc such memory in list (new them in constructor?).
I would like to use something like a ringbuffer with fixed size, allocated memories array and fifo principal.
Any idea how?
Edit1: Example pseudo code:
// called from writer thread
void receiveImage(const char *data, int length)
{
Image *image = images.nextStorage();
std::copy(data, data + length, image->data);
}
// prealloc
void preallocImages()
{
for (int i = 0; i < 100; i++)
images.preAlloc(new Image(400, 400));
}
// consumer thread
void imageProcessing()
{
Image image = image.WaitAndGetImage();
// ... todo
}
Say you create an Image
class to hold the data for an image, having a ring buffer amounts to something like:
std::vector<Image> images(100);
int next = 0;
...
while (whatever)
{
images[next++] = get_image();
next %= images.size();
}
You talk about preallocating memory: each Image
constructor can own the task of preallocating memory for its own image. If could do that with new
, or if you have fixed-size images that aren't particularly huge you could try a corrspondingly sized array in the Image
class... that way the all image data will be kept contiguously in memory - it might be a little faster to iterate images "in order". Note that simply having allocated virtual addresses doesn't mean there's physical backing memory yet, and that stuff may still be swapped out into virtual memory. If you have memory access speed issues, you might want to think about scanning over the memory for an image you expect to use shortly before using it or using OS functions to advise the OS of your intended memory use patterns. Might as well get something working and profile it first ;-).
For FIFO handling - just have another variable also starting at 0, if it's != next
then you can "process" the image at that index in the vector, then increment the variable until it catches up with next
.