TBB:parallel_for 中的局部和全局结果
我有一个关于并行循环中的局部值和更新全局变量的问题。
例如,在伪代码中:我正在一个很长的向量中搜索最大值。我可以在循环中执行此操作,如下所示:
int max;
for(i ...) {
if (max < vector[i]) max = vector[i];
}
我可以轻松地将其与 OpenMP 并行化:
int max;
#pragma omp parallel
{
int local_max;
#pragma omp parallel for
for(i ...) {
if (local_max < vector[i]) local_max = vector[i];
}
#pragma omp critical
{
// choose the best solution from all
if (max < local_max) max = local_max; local_max
}
}
如何在 TBB parallel_for
中执行相同操作?我不要求确切的代码,我只想知道如何在循环结束时更新全局结果,而不是在每次迭代时更新......
(我是 TBB 新手)
I have a question regarding local values in a parallel loop, and updating a global variable.
Example, in pseudo-code: I am searching for a maximum value in a very long vector. I can do it in a loop, like that:
int max;
for(i ...) {
if (max < vector[i]) max = vector[i];
}
I can easily parallelize it with OpenMP:
int max;
#pragma omp parallel
{
int local_max;
#pragma omp parallel for
for(i ...) {
if (local_max < vector[i]) local_max = vector[i];
}
#pragma omp critical
{
// choose the best solution from all
if (max < local_max) max = local_max; local_max
}
}
How can I do the same in TBB parallel_for
? I don't request an exact code, I would like just to know how to update the global result at the end of the loop, not at every iteration...
(I am new to TBB)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在此示例中执行的操作称为缩减,因此请使用
parallel_reduce
。它应该比更新锁下的全局变量更有效。基本思想是,local_max
是parallel_reduce
的body类的成员变量,它的join()
方法接收body的另一个实例并将local_max
更新为当前值和另一个实例中的值中的较大者。然后在调用parallel_reduce之后,从原始主体对象中取出local_max
值并将其分配给全局变量。What you do in this example is called reduction, so use
parallel_reduce
. It should be more efficient than updating a global variable under a lock. The basic idea is thatlocal_max
is a member variable of the body class forparallel_reduce
, and itsjoin()
method receives another instance of the body and updateslocal_max
to be the bigger of the current value and the value in the other instance. Then after the call to parallel_reduce you take thelocal_max
value out of the original body object and assign it to the global variable.