首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >openMP运动omp_bug2.c

openMP运动omp_bug2.c
EN

Stack Overflow用户
提问于 2014-02-08 17:18:29
回答 1查看 273关注 0票数 0

这是OpenMP网站上的一个练习:https://computing.llnl.gov/tutorials/openMP/exercise.html

代码语言:javascript
复制
#include "stdafx.h"
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

int _tmain(int argc, _TCHAR* argv[])
{
int nthreads, i, tid;
float total;

/*** Spawn parallel region ***/
#pragma omp parallel private(i, tid) // i changed this line 
  {
  /* Obtain thread number */
  tid = omp_get_thread_num();
  /* Only master thread does this */
  if (tid == 0) {
    nthreads = omp_get_num_threads();
    printf("Number of threads = %d\n", nthreads);
    }
  printf("Thread %d is starting...\n",tid);

  #pragma omp barrier

  /* do some work */
  total = 0.0;
  #pragma omp for schedule(dynamic,10) 
  for (i=0; i<1000000; i++)
     total = total + i*1.0;

  printf ("Thread %d is done! Total= %e\n",tid,total);

  } 
}

它的输出是

代码语言:javascript
复制
Number of threads = 4
Thread 0 is starting...
Thread 3 is starting...
Thread 2 is starting...
Thread 1 is starting...
Thread 0 is done! Total= 0.000000e+000
Thread 3 is done! Total= 0.000000e+000
Thread 2 is done! Total= 0.000000e+000
Thread 1 is done! Total= 0.000000e+000

这意味着变量"total"有问题。

这是网站上的帮助

这是我的解决方案:你认为这是正确的方法吗?

代码语言:javascript
复制
#include "stdafx.h"
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

int _tmain(int argc, _TCHAR* argv[])
{
int nthreads, i, tid;
float total;

/*** Spawn parallel region ***/
#pragma omp parallel private(total,tid)
  {
  /* Obtain thread number */
  tid = omp_get_thread_num();
  total= 0.0;
  /* Only master thread does this */
  if (tid == 0) {
    nthreads = omp_get_num_threads();
    printf("Number of threads = %d\n", nthreads);
    }
  printf("Thread %d is starting...\n",tid);



  #pragma omp parallel for schedule(static,10)\
  private(i)\
  reduction(+:total)
  for (i=0; i<1000000; i++) 
     total = total + i*1.0;

  printf ("Thread %d is done! Total= %e\n",tid,total);

  } /*** End of parallel region ***/
}

以下是我的新成果:

代码语言:javascript
复制
Number of threads = 4
Thread 0 is starting...
Thread 1 is starting...
Thread 0 is done! Total= 4.999404e+011
Thread 2 is starting...
Thread 1 is done! Total= 4.999404e+011
Thread 2 is done! Total= 4.999404e+011
Thread 3 is starting...
Thread 3 is done! Total= 4.999404e+011
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-08 17:50:37

是的,您当然希望total是一个线程私有变量。在实际示例中,您可能要做的一件事是将线程私有totals减少到一个全局总数(然后只让一个线程打印结果)。其中一种方法是简单的

代码语言:javascript
复制
#pragma omp atomic
global_total += total

最后(有更好的方法,尽管使用削减)。

PS:omp for的循环计数器在默认情况下是私有的,因此您实际上不必显式地指定它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21649207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档