2
votes

I have an application that continuously std::vector::push_back elements into a vector. As it is a real-time system I cannot afford it to stall at any time. Unfortunately, when the reserved memory is exhausted the push_back automatic memory allocation does cause stalls (up to 800ms in my measurements).

I have tackled the problem by having a second thread that monitors when the available memory and calls a std::vector::reserve if necessary.

My question is: is it safe to execute reserve and push_back concurrently?

(clearly under the assumption that the push_back will not reallocate memory)

Thanks!

2
Using a data structure which might grow by allocating memory and requiring real-time semantics is a contradiction in my book. There is no fixed upper bound on the duration of a memory allocation. - Micha Wiedenmann
You clearly use the wrong data structure. You need a concurrent, non-blocking queue. Unfortunately, the standard library doesn't provide it. You may be able to use the "thread building blocks" library. - stefan

2 Answers

2
votes

It is not thread-safe because a vector is contiguous and if it gets larger then you might need to move the contents of a vector to a different location in memory.

As suggested by stefan, you can look at non-blocking queues or have a list (or vector) of vectors such that when you need more space, the other thread can reserve a new vector for you while not blocking the original for lookups. You would just need to remap your indices to look up into the correct vector within the list.

-5
votes

No.

Thread-safety concept exists only in C++11. And it is defined in relation to const. In C++11 standard library const now means thread-safe. Neither of those 2 methods is const, so no, it is not thread-safe.