I’m new in the world of parallel computing and dong many researches in data races and how to avoid those. The concept is quite clear to me, but I would have a question regarding the use of std::vector and modifications of their items by different threads.
So, I have this vector of vectors and pass a pointer to each element of the vector to a thread, such thread does some things and at the end swap the content of a new vector with the original one. Each thread can operates only on a single element of the vector and the vector is not modified in its size (no push back, po, etc.). I think this is thread safe (also looking to other questions on SO), but since it involves vector of vectors I would like to ask your opinion to understand whether there could be any drawback.
So, definitive question: is the following code thread safe??
`#include <vector>
#include <thread>
#include <list>
void func(std::vector<int> *vec_ptr)
{
std::vector<int> other_vec;
other_vec.emplace_back(1);
other_vec.emplace_back(20);
vec_ptr->swap(other_vec);
}
int main()
{
std::vector<std::vector<int>> vector;
vector.reserve(6);
for (int i = 0; i < 6; i++)
{
std::vector<int> vec_loc;
vec_loc.emplace_back(1);
vec_loc.emplace_back(2);
vec_loc.emplace_back(3);
vector.emplace_back(vec_loc);
}
std::list<std::thread> threads;
for (int i = 0; i < 6; i++)
{
threads.push_back(std::thread(func));
}
for (auto thread_iter = threads.begin(); thread_iter != threads.end(); thread_iter++)
{
thread_iter->join();
}
}`
The code runs fine, but I would like to go deeper and be sure that what I wrote is correct and there are no drawbacks (for example I read about problems with std::vector). Please consider that could be also interesting to fill the vector not with int bu with custom classes (that could be big).