线程安全性std :: vector push_back并保留
我有一个应用程序,可以将 std :: vector :: push_back 元素连续地向量化.由于它是实时系统,因此我无法承受.不幸的是,当保留的内存用尽时,push_back自动内存分配确实会导致停顿(在我的测量中长达800ms).
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).
我已经解决了这个问题,它有一个第二个线程来监视可用内存的时间,并在必要时调用 std :: vector :: reserve .
I have tackled the problem by having a second thread that monitors when the available memory and calls a std::vector::reserve if necessary.
我的问题是:同时执行储备金和push_back是否安全?
My question is: is it safe to execute reserve and push_back concurrently?
(显然是在push_back不会重新分配内存的前提下)
(clearly under the assumption that the push_back will not reallocate memory)
谢谢!
它不是线程安全的,因为向量是连续的,如果向量变大,则可能需要将向量的内容移动到内存中的其他位置
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.
如stefan所建议,您可以查看非阻塞队列或有一个向量列表(或向量),这样,当您需要更多空间时,另一个线程可以为您保留一个新向量,而不会阻塞原始向量.查找.您只需要重新映射索引即可在列表中查找正确的向量.
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.