c++ - 如何进行并行双线性插值

标签 c++ c multithreading parallel-processing openmp

我试过这个,但我不知道它是否正确,并且计算执行时间有时它会给我 0
在代码中。
我首先创建了一个结构来存储要插值的点的所有坐标我有一个要插值的点表,所以我使用了pragma parallel for执行 for 部分以插入所有点。变量 R1、R2 和 P 是 double 变量,并且在线程之间共享。

  #pragma omp parallel for
  for(i=0;i<N ; i++)
  {
     R1 =  BilinearInterpolation(Table[i].x1, Table[i].Q11,Table[i].x2, Table[i].Q21,Table[i].x);
     R2 =  BilinearInterpolation(Table[i].x1, Table[i].Q12, Table[i].x2, Table[i].Q22,Table[i].x);
     P =  BilinearInterpolation(Table[i].y1,  R1, Table[i].y2,  R2, Table[i].y);
     TableInter[i] = P;
  }

最佳答案

 #pragma omp parallel for
 for(i=0;i<N ; i++)
 {
      R1 = BilinearInterpolation(Table[i].x1, Table[i].Q11,Table[i].x2, Table[i].Q21,Table[i].x);
      R2 = BilinearInterpolation(Table[i].x1, Table[i].Q12, Table[i].x2, Table[i].Q22,Table[i].x);
      P =  BilinearInterpolation(Table[i].y1,  R1, Table[i].y2,  R2, Table[i].y);
      TableInter[i] = P;
 }
您的代码的问题是 R1 , R2 , 和 P由多个线程共享和更新,因此您有竞争条件。例如,一个线程可能正在更改 P而另一个添加 PTableInter[i] .尽管如此,您可以通过将这些变量声明为私有(private)变量(即在并行区域内声明它们)或使用 OpenMP 的 private 轻松解决这种竞争条件。子句(#pragma omp parallel for private(R1, R2, P)。
 #pragma omp parallel for private(R1, R2)
 for(i=0;i<N ; i++)
 {
      R1 = BilinearInterpolation(Table[i].x1, Table[i].Q11,Table[i].x2, Table[i].Q21,Table[i].x);
      R2 = BilinearInterpolation(Table[i].x1, Table[i].Q12, Table[i].x2, Table[i].Q22,Table[i].x);
      TableInter[i] = BilinearInterpolation(Table[i].y1,  R1, Table[i].y2,  R2, Table[i].y);
 }
只要BilinearInterpolation方法不会修改线程之间的共享状态,此代码是无竞争条件的。

calculate the time of execution sometimes it gives me 0 in the code,


要计算时间,可以使用 OpenMP 函数 omp_get_wtime , 如下:
double start = omp_get_wtime();
// the code that you want to measure.
double end = omp_get_wtime();  
printf("%f\n",end-start);

关于c++ - 如何进行并行双线性插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65595876/

相关文章:

使用抽象接口(interface)的 C++ 编译器独立 DLL

iOS 多线程问题

c++ - 如何在 Spirit x3 中执行 no_case

c++ - 什么是 check_union256d?

c++ - 为什么我得不到虚拟打印机的上下文?

C gcc编译问题和makefile

windows - 在c/c++中使用检查函数编译Windows NT命令行代码循环

javascript - 我怎么知道我已经达到了 Node 中定义的线程限制?

java - 并发链表读取器/写入器无法正常工作

c++ - 在 Qt 应用程序启动之前设置系统环境变量