我正在写一个程序,其中一堆不同的类,所有存储在向量中,使用公共数据结构在私有成员上执行并行操作。我想为使用OpenMP的多个处理器并行化它,但是我有两个有关代码中两个操作的问题,下面的示例在下面的注释中指出了这两个问题,它们显示了程序逻辑的简化形式。是只读的全局变量和写入私人类成员在openmp中的“虚假共享”
#include <omp.h>
#include <iostream>
#include <sys/timeb.h>
#include <vector>
class A {
private :
long _i;
public :
void add_i(long &i) { _i += i; }
long get_i() const { return _i; }
};
int main()
{
timeb then;
ftime(&then);
unsigned int BIG = 1000000;
int N = 4;
std::vector<long> foo(BIG, 1);
std::vector<A *> bar;
for (unsigned int i = 0; i < N; i++)
{
bar.push_back(new A());
}
#pragma omp parallel num_threads(4)
{
for(long i = 0; i < BIG; i++)
{
int thread_n = omp_get_thread_num();
// read a global variable
long *to_add = &foo[i];
// write to a private variable
bar[thread_n]->add_i(*to_add);
}
}
timeb now;
ftime(&now);
for (int i = 0; i < N; i++)
{
std::cout << bar[i]->get_i() << std::endl;
}
std::cout << now.millitm - then.millitm << std::endl;
}
第一条评论涉及从全局foo读取。这是“虚假分享”(或数据晃荡)?我读的大部分资源都是关于写入操作方面的虚假共享,但我不知道读取操作是否也适用。
第二个注释解决了对bar中的类的写入操作。同样的问题:这是错误的分享?他们正在写入同一个全局数据结构中的元素(这是我读过的,晃荡),但只是在元素内部对私有数据进行操作。
当我与一个for循环替换OpenMP的宏,该程序是由约25%的速度,所以我猜我做错了什么......
你的例子很奇怪。你说过一堆不同的课程,但我认为你是指同一班级的一堆不同的对象?而你的意思是四个。这不是很多。但它也被设置为似乎任意的线程数。你为什么不向我们展示你的非并行代码,然后我们可以告诉你如何最好地并行化它。 –