2
Dec
0
C++ – OpenMP – Sum reduction example (simple example)
Here is an example of a reduction on a variable to sum the result from each thread.
The code
You can change the number of thread by changing “NB_THREAD_TEST”.
#include "stdafx.h"
#include <omp.h>
#include <iostream>
// number of thread for this simu
// we use it only to use many thread (more than cpu nb)
const int NB_THREAD_TEST = 6;
int _tmain(int argc, _TCHAR* argv[])
{
// sum of each thread
int sum = 0;
// parallel section with NB_THREAD_TEST and recution for the sum variable
// the reduction cumulate each results of each threads
#pragma omp parallel num_threads(NB_THREAD_TEST) reduction(+:sum)
{
// master thread prints the number of working thread
#pragma omp master
{
std::cout << "Number of threads = " << omp_get_num_threads() << std::endl;
}
// put the thread id into sum
sum = omp_get_thread_num();
}
// withou redution the sum will be the last thread id that wrote into the variable
// but here this is : sum = 4 + 3 + 2 + 1 + 0
std::cout << "Sum = " << sum << std::endl;
std::cout << "Sum should be = " << ( ((NB_THREAD_TEST)>>1) * ((NB_THREAD_TEST&0x01) + NB_THREAD_TEST - 1) ) << std::endl;
return 0;
}
Output
Number of threads = 6 Sum = 15 Sum should be = 15 Appuyez sur une touche pour continuer...
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
Subscribe to the RSS feed and have all new posts delivered straight to you.
