OpenMP实现数组并行相加

int main()
{
	int sum = 0;
	int a[] = {1,2,3,4,5,6,7,8};
	int coreNum = omp_get_num_procs();//获得处理器个数
	printf("处理器个数:%d\n", coreNum);
	int *sumArray = new int[coreNum]; //每一个处理器统计一部分总和
	for (int i=0; i<coreNum; ++i)
	{
		sumArray[i] = 0;
	}
#pragma omp parallel for
	for (int i=0; i<8; ++i)  // 8核CPU,每个核心做一个
	{
		int k = omp_get_thread_num();// 获得每个线程的ID
		printf("线程ID:%d\n", k);
	    sumArray[k] = sumArray[k] + a[i];
	}
	for (int i=0; i<coreNum; ++i)
	{
		sum = sum + sumArray[i];
	}
	std::cout << "sum: " << sum << std::endl;
	system("pause");
	return 0;
}

阅读更多
换一批

没有更多推荐了,返回首页