简体   繁体   English

OpenMP和不同的STL向量

[英]OpenMP and different STL vectors

Is this safe as is? 这样安全吗? Or we need to uncomment the "critical" pragma? 还是我们需要取消对“关键”实用主义的评论?

std::vector< std::vector<int> > vv(10);
#pragma omp parallel for
for (int i=0; i<10; ++i)
    for (int j=0; j<100; ++j)
        // Should we uncomment the following pragma?
        // #pragma omp critical
        vv[i].push_back(j);

The given code is safe as is because all threads will operate on different elements of vv . 给定的代码是安全的 ,因为所有线程将在vv不同元素上运行。 std::vector is weakly thread safe in the sense that you can operate concurrently on different vectors as you wish. std::vector是弱线程安全的,因为您可以根据需要同时对不同的vector进行操作。

Short answer 简短答案

Short answer: do not uncomment, it is safe without critical section 简短答案:不要取消注释,没有关键部分是安全的

Long Answer 长答案

There is no need for a critical section as echo thread is given a unique subset of iterations from the for loop (there are different strategies that you can apply for distributing them). 不需要关键部分,因为回显线程从for循环中获得了唯一的迭代子集(可以应用各种策略来分配它们)。 What is important for you is not having race conditions which happen when concurrenlty adding elements on the same vector ( push_back is not thread-safe per se). 对您而言重要的是没有在并发地在同一向量上添加元素时发生竞争的情况( push_back本身不是线程安全的)。

In your case each thread always and only access its own set of vectors, so there is no chance two thread write the same vector . 在您的情况下,每个线程始终且仅访问其自己的向量集,因此,两个线程不可能写入相同的vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM