你的代码有一些问题,即:
第一:
for(int i = 1; i < 101; i++){
a[i] = i;
}
您已将数组a 分配为int a[100];,因此在您的循环中您正在获取数组边界,将其更改为:
for(int i = 0; i < 100; i++){
a[i] = i + 1;
}
第二:
int nthreads = 5
...
/* Fork a team of threads giving them their own copies of variables */
#pragma omp parallel private(nthreads, tid)
nthreads = omp_get_num_threads();
这毫无意义。您创建一个并行区域,所有线程都有nthreads 的副本,他们将该变量设置为线程数,但在并行区域之后该值消失了。之后打印5 的唯一原因:
printf("Number of threads = %d\n", nthreads);
是因为 nthreads 最初设置为 5。
第三:
for(int i = 0; i < 100; i++){
sum = sum + a[i + 1];
}
您再次访问数组a之外的位置,将其更改为:
for(int i = 0; i < 100; i++){
sum = sum + a[i];
}
第四:
我正在尝试仅使用 5 来获得从 1 到 100 的数字总和
即使我有 12 个可用线程。
因为你没有指定并行区域的线程数:
#pragma omp parallel for reduction (+:sum)
您的代码使用 12 个线程运行。
我想要的输出如下:
总和是 5050 而不是 4950 有没有办法输出
每个线程的本地总和?
你想要做的是:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int sum = 0;
int a[100];
for(int i = 0; i < 100; i++){
a[i] = i + 1;
}
int total_threads_used;
// Create a parallel region with 5 threads and reduce the partial sum's values
#pragma omp parallel num_threads(5) reduction (+:sum)
{
total_threads_used = omp_get_num_threads(); // Get the total threads used
#pragma omp for
for(int i = 0; i < 100; i++){
sum = sum + a[i];
}
printf("Current thread is %d and SUM %d\n", omp_get_thread_num(), sum);
}
printf("Number of threads = %d\n", total_threads_used);
printf("The total sum is %d\n\n\n", sum);
}
输出:
Current thread is 0 and SUM 210
Current thread is 2 and SUM 1010
Current thread is 1 and SUM 610
Current thread is 3 and SUM 1410
Current thread is 4 and SUM 1810
Number of threads = 5
The total sum is 5050
这些行将在每次运行中以不同的顺序输出,因为这些行是并行打印的,但无论运行如何,您都应该有 5 个 "Current thread is" 从 0 到 4、1 个 "Number of threads = 5" 和 1 个 @ 987654338@.