gpt4 book ai didi

c++ - openMP 练习 omp_bug2.c

转载 作者:行者123 更新时间:2023-11-28 07:06:56 25 4
gpt4 key购买 nike

这是来自 OpenMP 网站的练习: https://computing.llnl.gov/tutorials/openMP/exercise.html


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

}
}

这个的输出是

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"

有问题

这是网站上的帮助 enter image description here

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

#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 ***/
}

这是我的新输出:

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

最佳答案

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

#pragma omp atomic
global_total += total

在最后(虽然使用减少有更好的方法)。

PS:omp for 的循环计数器默认是私有(private)的,因此您实际上不必明确指定。

关于c++ - openMP 练习 omp_bug2.c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21649207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com