我一直在尝试创建一个多线程程序,它计算从1到999之间的3和5的倍数,但是每次运行它时,我似乎都不能正确地得到它,我想它可能与我使用一个共享变量和10个线程有关,但我不知道如何绕过它。此外,如果我计算3和5的倍数从1到9,程序也能工作。
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
#include <string.h>
#define NUM_THREADS 10
#define MAX 1000
//finds multiples of 3 and 5 and sums up all of the multiples
int main(int argc, char ** argv)
{
omp_set_num_threads(10);//set number of threads to be used in the parallel loop
unsigned int NUMS[1000] = { 0 };
int j = 0;
#pragma omp parallel
{
int ID = omp_get_thread_num();//get thread ID
int i;
for(i = ID + 1;i < MAX; i+= NUM_THREADS)
{
if( i % 5 == 0 || i % 3 == 0)
{
NUMS[j++] = i;//Store Multiples of 3 and 5 in an array to sum up later
}
}
}
int i = 0;
unsigned int total;
for(i = 0; NUMS[i] != 0; i++)total += NUMS[i];//add up multiples of 3 and 5
printf("Total : %d\n", total);
return 0;
}发布于 2015-04-10 00:16:27
您遇到的问题是线程不需要按顺序执行,所以最后一个要连线的线程可能没有按顺序读取值,所以您重写了错误的数据。
有一个表单来设置一个循环中的线程,当它们用openmp选项结束时做一个验证。你必须用这种方法才能使用它。
#pragma omp parallel for reduction(+:sum)
for(k=0;k<num;k++)
{
sum = sum + A[k]*B[k];
}
/* Fin del computo */
gettimeofday(&fin,NULL);你所要做的就是用"sum“写结果,这是我用的一段旧代码,做了一次实验。
你的另一个选择是肮脏的。某种程度上,使用对操作系统的调用,让线程等待并排序。这比看起来容易多了。这将是一个解决办法。
#pragma omp parallel
for(i = ID + 1;i < MAX; i+= NUM_THREADS)
{
printf("asdasdasdasdasdasdasdas");
if( i % 5 == 0 || i % 3 == 0)
{
NUMS[j++] = i;//Store Multiples of 3 and 5 in an array to sum up later
}
}但我建议你充分阅读openmp的选项。
https://stackoverflow.com/questions/29550878
复制相似问题