简体   繁体   English

如何使用openMP将顺序程序转换为并行程序?

[英]how can i convert a sequential program to parallel using openMP?

I'm beginning in openMP and i want parallelize this portion of code : 我从openMP开始,我想并行化这部分代码:

for (i=0 ;i<n ;i++) 
  for (j=1 ;j<n ;j++)  
    A[i][j]+=A[i][j-1];

How can i make this for parallel? 我怎样才能使这个for并行?

I recommend you start by checking out the following link: http://bisqwit.iki.fi/story/howto/openmp/ . 我建议您首先查看以下链接: http : //bisqwit.iki.fi/story/howto/openmp/ It gives a brief overview of what you can achieve using OpenMP. 它简要概述了使用OpenMP可以实现的目标。

For your code fragment parallelising can be as easy as writing one pragma: 对于您的代码片段,并行化就像编写一个编译指示一样容易:

#pragma omp parallel for private(i, j) shared(A, n)
for (i = 0; i < n; ++i) 
  for (j = 1; j < n; ++j)  
    A[i][j] += A[i][j-1];

That is the idea behind OMP: you annotate your program with messages, that allow the code to be compiled and linked with OMP and then ran in parallel, or compiled ignoring the pragmas in which case the program should remain a valid sequential program. 这就是OMP背后的思想:用消息注释程序,该消息允许代码被编译并与OMP链接,然后并行运行,或者忽略编译指示而编译,在这种情况下,程序应保持有效的顺序程序。

In this case the pragma leaves the decision as to how many threads to run to the runtime. 在这种情况下, pragma将决定运行多少线程来运行。 The runtime generally makes a decision based on the amount of cores in the machine. 运行时通常根据计算机中的内核数量进行决策。 The outer loop will be parallelized and each i iteration will conceptually be performed by a different thread. 外循环将并行化,并且从概念上讲,每个i迭代将由不同的线程执行。 This is important because you have data dependencies between various j iterations, and communication/synchronization in parallel is tricky. 这很重要,因为您在各个j迭代之间都具有数据依赖性,并且并行通信/同步非常棘手。 Keeping the inner loop within a thread deals with this problem. 将内部循环保留在线程内可解决此问题。 The shared section could be left out because things are shared by default. shared部分可能被忽略,因为默认情况下是共享的。 But for this reason exactly you shouldn't leave it out: be explicit about what you want shared and what you want private. 但是出于这个原因,您不应该忽略它:明确要共享的内容和私有的内容。 This is a good way to avoid many bugs that happen when writing parallel code. 这是避免编写并行代码时发生许多错误的好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM