Search code examples
c++multithreadingvector

Thread safety std::vector push_back and reserve


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!


Solution

  • 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.