我需要帮助理解这个openMP示例 [英] I need help understanding this openMP example

查看:129
本文介绍了我需要帮助理解这个openMP示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在openMP,我想并行化这部分代码:

I'm beginning in openMP and I want parallelize this portion of code :

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

我发现这个答案:

#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];

我有一些问题:


  • 为什么 i 不公开?

  • 关于这个答案,如果我有4个线程,因此每个线程执行相同的代码,我不明白如何获得与序列代码相同的结果?

  • why does i private and not shared?
  • about this answer if i have 4 threads so each thread executes the same code, I don't understand how can I obtain a same result as sequential code ?

线程如何实现这项工作?我需要你的帮助。

How do threads achieve this work? I need your help.

推荐答案


为什么 i 私人且不分享?

变量 i j 是每个线程的私有,因为它们是循环计数器。每个线程必须跟踪它正在做什么,与其他线程分开。如果 i j 在线程之间共享,那么每个线程都会更新它们并且乱乱其他线程的执行。

The variables i and j are private to each thread because they are loop counters. Each thread has to keep track of what it is doing, separately from other threads. If i or j were shared among threads, then each thread would update them and mess with the execution of other threads.


如果我有4个线程,因此每个线程执行相同的代码,我不明白如何获得与顺序代码相同的结果?

if i have 4 threads so each thread executes the same code, I don't understand how can I obtain a same result as sequential code ?

每个线程执行相同的代码行,但使用不同的变量。 OpenMP的'for'指令有助于在线程之间自动分配迭代,以便每个线程获得不同的起始值 i 和不同的结束值在 for 循环。因此,它更像是每个线程在 循环中获得相同的代码,但不同的循环初始化和结束条件。所有它们一起(如果编程正确)给出与顺序实现相同的最终结果。

Each thread executes the same lines of code, but using different variables. OpenMP's 'for' directive helps to automagically distribute the iterations among threads, so that each thread gets a different starting value of i and a different ending value in the for loop. So it's more like each thread gets the same code inside the loop, but different loop initialization and end condition. All of them together will (if programmed correctly) give the same end result as a sequential implementation.

当然,为了这个工作,循环是必要的可并行化。如果循环的每次迭代都取决于先前迭代计算的结果,那么它不能并行运行。在这种情况下,您需要重写循环,以便每次迭代都可以独立运行。

Of course, for this to work it is necessary for the loop to be parallelizable. If each iteration of the loop depends on results calculated by previous iterations, then it can't be run in parallel. In that case you'll need to rewrite the loop so that each iteration can be run independently.

这篇关于我需要帮助理解这个openMP示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆