I would like two threads work like this:
- First thread will append values to vector
- Second thread will have read-only access to elements by index
I can make mutex and make deep copy before second thread start reading…. But this way is really slow… How is it possible to make this without mutex? Here: STL vector and thread-safety
I read that it is possible to use std::deque, but it fails like std::vector …
Where I can find append-only container, which don’t realloc data?
I have solved my problem by creating own container GrowVector with operations: adding elements to back, getting size, accessing element by index. It works for 2Billion elements for default, but it can be changed by constructor parameter.
#include <vector>
template<typename T>
class GrowVector
{
std::vector<std::vector<T> > m_data;
size_t m_size;
public:
GrowVector(int chunks = 32768)
: m_data()
, m_size(0)
{
m_data.reserve(chunks);
m_data.push_back(std::vector<T>());
m_data.back().reserve(1 << 16);
}
void add(const T & value)
{
if (m_data.back().size() == m_data.back().capacity())
{
m_data.push_back(std::vector<T>());
m_data.back().reserve(1 << 16);
}
m_data.back().push_back(value);
m_size++;
}
size_t size() const
{
return m_size;
}
T & operator [] (int i)
{
return m_data[i >> 16][i & 0xffff];
}
const T & operator [] (int i) const
{
return m_data[i >> 16][i & 0xffff];
}
};
Is my solution safe?
Your solution is not thread-safe without a locking mechanism.
You can use tbb::concurrent_vector or Concurrency::concurrent_vector for multiple insertion and access simultaneously. No extra locking required. It is unsafe to erase elements from those vectors, but you are ok with it I guess.