OpenMP和STL向量 [英] OpenMP and STL vector

查看:518
本文介绍了OpenMP和STL向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,我想使用OpenMP的方式如下:

I've got some code for which I'd like to use OpenMP in the following way:

std::vector<int> v(1000);
# pragma omp parallel for
for (int i = 0; i < 1000; ++i) {
    v[i] = i;
}



我读过STL向量容器不是线程安全的情况下多线程写入单个容器,这意味着我需要在进行任何写入之前锁定向量;然而,我也被告知,上面的写操作是某种原子,所以没有上面的竞态条件。

I have read that STL vector container is not thread-safe in the situation where multiple threads write to a single container, which would imply that I'd need to lock the vector before making any writes; however, I've also been told that the write operation above is somehow "atomic", and so there is no race condition above. Could someone clarify this?

推荐答案

在这个特定的例子中,它是安全的。

In this particular example, it will be safe.

原因是你没有使用可能导致重新分配的操作。 (例如 push_back())您只更改单个元素的内容。

The reason is that you're not using operations that could cause a reallocation. (such as push_back()) You're only changing the contents of the individual elements.

可以合法地执行此操作:

Note that you can just at legally do this:

std::vector<int> v(1000);
int *ptr = &v[0];

# pragma omp parallel for
for (int i = 0; i < 1000; ++i) {
    ptr[i] = i;
}






-safe当你开始调用 push_back() pop_back() insert ),etc ...。


It becomes not-thread-safe when you start calling methods like push_back(), pop_back(), insert(), etc... from multiple threads.

我还要补充一点,这个特定的例子不太适合并行化,因为几乎没有任何工作要做。但我想这只是一个下沉的例子,为了提出这个问题的目的。

I'll also add that this particular example isn't well-suited for parallelism since there's hardly any work to be done. But I suppose it's just a dumbed-down example for the purposes of asking this question.

这篇关于OpenMP和STL向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆