在仍在使用OpenMP的功能的同时,如何获得私人向量?
我试图与OpenMP并行化我的代码。
我有一个全球向量,因此我可以用自己的功能过多。 有什么方法可以使矢量的副本与每个线程相关,以便他们可以使用它? 是描述我的问题的一些
double var = 1;
std::vector<double> vec;
void function()
{
vec.push_back(var);
return;
}
int main()
{
omp_set_num_threads(2);
#pragma omp parallel
{
#pragma omp for private(vec)
for (int i = 0; i < 4; i++)
{
function();
}
}
return 0;
}
码
- 假
- 这 在向量(更改特定值)上的工作
- (在我的原始代码中,有许多向量和功能,IVE只是试图解决问题)
IVE尝试了#pragma op threadprivate(),但这仅适用于变量而不是对矢量。 同样,对矢量进行重新启动并不有所帮助,因为我的功能始终与全局矢量一起使用,然后当不同的胎面同时称其为问题时,这会导致问题。
Im trying to parallelize my code with openmp.
I have a global vector, so i can excess it with my functions.
Is there a way that i can asign a copy of the vector to every thread so they can do stuff with it?
Here is some pseudocode to describe my problem:
double var = 1;
std::vector<double> vec;
void function()
{
vec.push_back(var);
return;
}
int main()
{
omp_set_num_threads(2);
#pragma omp parallel
{
#pragma omp for private(vec)
for (int i = 0; i < 4; i++)
{
function();
}
}
return 0;
}
Notes:
- i want each tread to have an own vector, to safe specific values, which later only the same thread needs to excess
- each thread calls a function (sometimes its the same) which then does some work on the vector (changing specific values)
- (in my original code there are many vectors and functions, ive just tried to break the problem down)
Ive tried #pragma omp threadprivate(), but that only works for varibles and not for vectors.
Also redeclaring the vector inside the parallel region doesnt help, as my function always works with the global vector, which then leads to problems when different treads call it at the same time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的, firstprivate 条款条款可以做到这一点:
因此,它为每个线程创建一个变量的私有副本,但是该私有变量的范围是OpenMP构造之后的结构化块。在此块之外,您可以访问全局变量:
如果您希望在函数中使用变量的私有副本,则必须将其传递给您的函数:
但是,请注意,如@Jeromerichard所指出的那样,您应该应该不使用代码中的全局变量。
Yes, the firstprivate clause does this:
So, it creates a private copy of the variable for each thread, but the scope of this private variable is the structured block following the OpenMP construct. Outside this block you access the global variable:
If you wish to use the private copy of your variable in a function you have to pass it as a reference to your function :
Note that, however, as pointed out and explained by @JeromeRichard you should not use global variables in your code.