Lets say I have a 2D array and this function:
void addVec(std::vector<std::vector<short> >& arr, size_t idx){
arr[idx].push_back(idx);
}
std::vector<std::vector<short> > arr(2);
boost::threads th1(addVec, boost::ref(arr), 0);
boost::threads th2(addVec, booost::ref(arr), 1);
th1.join();
th2.join();
By now I should have arr[0][0] = 0; and arr[1][0] = 1;
The questions is if this is safe?
Internally the threads should add values to different parts of vector memory, and because it is constructed at the beginning of size 2 only the internal vectors get resized, witch have thread exclusive access.
Yes, it is safe in your use case, because you don’t modify the shared data. However, I would prefer to pass the reference to the
std::vector<short>to each thread to simplify the usage: