【发布时间】:2010-07-20 17:10:27
【问题描述】:
不明白,我哪里弄错了。如果在没有 openmp 支持的情况下编译,代码可以正常工作。但是使用 openmp 变量似乎得到了错误的可见性。
我有以下意图。每个线程都有自己的 max_private,它可以在其中找到局部最大值。然后在临界区找到全局最大值。
#include <iostream>
#include <vector>
typedef std::vector<long> Vector;
long max(const Vector& a, const Vector& b)
{
long max = 0;
#pragma omp parallel
{
long max_private = 0;
#pragma omp single
{
for ( Vector::const_iterator a_it = a.begin();
a_it != a.end();
++a_it)
{
#pragma omp task
{
for ( Vector::const_iterator b_it = b.begin();
b_it != b.end();
++b_it)
{
if (*a_it + *b_it > max_private) {
max_private = *a_it + *b_it;
}
}
}
}
}
#pragma omp critical
{
std::cout << max_private << std::endl;
if (max_private > max) {
max = max_private;
}
}
}
return max;
}
int main(int argc, char* argv[])
{
Vector a(100000);
Vector b(10000);
for (long i = 0; i < a.size(); ++i) {
a[i] = i;
}
for (long i = 0; i < b.size(); ++i) {
b[i] = i * i;
}
std::cout << max(a, b) << std::endl;
return 0;
}
我不想使用并行,因为后者我将使用不支持随机访问迭代器的数据结构。
我用的是g++-4.4编译器。
【问题讨论】:
标签: c++ multithreading openmp