Advertisement
alexbuisson

A simple OpenMP example

Aug 2nd, 2013
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. /*
  2. * SimpleForDirective.cpp
  3. * F=OpenMpDemo && g++ -c $F.cpp -o $F.o -fopenmp -std=c++0x && g++ $F.o -o $F.exe -fopenmp && ./$F.exe
  4. */
  5.  
  6. #include <iostream>
  7. #include <iterator>
  8. #include <algorithm>
  9. #include <vector>
  10. #include <stdio.h>
  11.  
  12. using namespace std;
  13.  
  14. void sequential(int *a, int size, int *b)
  15. {
  16.     int i;
  17.     for (i = 0; i < size; i++) {
  18.         b[i] = a[i] * i;
  19.     }
  20. }
  21.  
  22. void parallel_for(int *a, int size, int *b)
  23. {
  24. #pragma omp parallel for
  25.     for (int i = 0; i < size; i++) {
  26.         b[i] = a[i] * i;
  27.     }
  28. }
  29.  
  30. void parallel_for_with_an_usage_error(int *a, int size, int *b)
  31. {
  32.     int j;
  33. #pragma omp parallel for
  34.     for (int i = 0; i < size; i++) {
  35.         /*int*/ j = a[i]; //To be correct j should be declared here, in-loop to be private !
  36.         j *= i;
  37.         b[i] = j;
  38.     }
  39. }
  40.  
  41. #define SIZE 9999
  42. //#define DUMP_ARRAY
  43.  
  44. int main(int ac, char** av)
  45. {
  46.     cout << "OpenMP Demo Simple For Directive and sharing example....." << endl;
  47.     int a[SIZE]; int root = 1; generate(a, a+SIZE, [&root](){return ++root;});
  48.     int b[SIZE]; fill(b, b+SIZE, 0);
  49.  
  50.     sequential(&a[0], SIZE, b);
  51. #ifdef DUMP_ARRAY
  52.     copy(b, b + SIZE, ostream_iterator<int>(cout, " ")), cout << endl;
  53. #endif
  54.     int reference[SIZE]; copy(b, b + SIZE, reference);
  55.  
  56.     /*parallel_for(&a[0], SIZE, b);
  57. #ifdef DUMP_ARRAY
  58.     copy(b, b + SIZE, ostream_iterator<int>(cout, " ")), cout << endl;
  59. #endif
  60.     //*/
  61.  
  62.     parallel_for_with_an_usage_error(&a[0], SIZE, b);
  63. #ifdef DUMP_ARRAY
  64.     copy(b, b + SIZE, ostream_iterator<int>(cout, " ")), cout << endl;
  65. #endif
  66.     //*/
  67.  
  68.     if(!equal(b, b+SIZE, reference)){
  69.         cout << "error .... " << endl;
  70.     } else {
  71.         cout << "ok .... " << endl;
  72.     }
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement