Parallel push back to a vector of vector

use*_*119 4 c++ openmp thread-safety

I have a vector of vector. I construct this vector in a parallel manner with each index in the vector being dealt with by a single thread. Something similar to this :

vector<vector<int> > global_vec(10, vector<int>({}));

#pragma omp parallel for schedule(dynamic)
for(int i = 0; i < 10; i++)
{
    for(int j = 0; j < i * 5; j++)
    {
        global_vec[i].push_back(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

I know if I had known the size of each vector beforehand, I could have allocated required size in the beginning and then there would have been no issue. But this can't be done by me and I need to dynamically push back. Is this thread safe?

Thanks in advance.

sch*_*312 5

是的,这是线程安全的,因为内部向量仅由一个线程修改。您可以省略schedule(dynamic)导数,但仍然可以保存。

如果您使用摆脱了内部循环,这将变得更加清晰std::iota

vector<vector<int> > global_vec(10, vector<int>({}));

#pragma omp parallel for schedule(dynamic)
for(int i = 0; i < 10; i++)
{
    global_vec[i].resize(i * 5) ;
    std::iota(global_vec[i].begin(), global_vec[i].end(), 0);
}
Run Code Online (Sandbox Code Playgroud)

附言 如果外部向量的大小固定,请考虑使用a std::array<vector<int>, 10>代替。