ostyleo

Untitled

Jan 23rd, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <omp.h>
  4.  
  5. #define SIZE 10
  6. #define NUMBER_OF_THREADS 4
  7.  
  8. void add_vectors(const int* v1, const int* v2, int* rez)
  9. {
  10.     int sum = 0;
  11. #pragma omp parallel if(SIZE > 5) default(none) shared(v1, v2, rez, sum)
  12.     {
  13. #pragma omp for schedule(guided, 2) reduction(+: sum)
  14.         for (auto i = 0; i < SIZE; ++i)
  15.         {
  16.             sum = sum + v1[i] * v2[i];
  17.             rez[i] = v1[i] + v2[i];
  18.             printf("I am thread %d at %d\n", omp_get_thread_num(), i);
  19.         }
  20.     }
  21.     printf("I am sum: %d\n", sum);
  22. }
  23.  
  24. void f(int* p_value, const int number_of_executions)
  25. {
  26.     for (auto i = 0; i < number_of_executions; ++i)
  27.     {
  28. #pragma omp critical (p_value)
  29.         {
  30.             (*p_value)--;
  31.         }
  32.     }
  33.     printf("I am function F from thread %d\n", omp_get_thread_num());
  34. }
  35.  
  36. void g(int* p_value, const int number_of_executions)
  37. {
  38.     for (auto i = 0; i < number_of_executions; ++i)
  39.     {
  40. #pragma omp critical (p_value)
  41.         {
  42.             (*p_value)++;
  43.         }
  44.     }
  45.     printf("I am function G from thread %d\n", omp_get_thread_num());
  46. }
  47.  
  48. void print_rez_ex1(const int* rez)
  49. {
  50.     printf("\n");
  51.     for (auto i = 0; i < SIZE; ++i)
  52.     {
  53.         printf("REZ[%d] = %d\n", i, rez[i]);
  54.     }
  55. }
  56.  
  57. int main()
  58. {
  59.     omp_set_num_threads(NUMBER_OF_THREADS);
  60.  
  61.     //-------------------------------------- EX 1 --------------------------------------
  62.     printf("------------------ EX 1 -------------------\n");
  63.     int v1[SIZE], v2[SIZE], v3[SIZE];
  64.     for (auto i = 0; i < SIZE; ++i)
  65.     {
  66.         v1[i] = i;
  67.         v2[i] = 1;
  68.     }
  69.  
  70.     add_vectors(v1, v2, v3); // ADD
  71.     print_rez_ex1(v3); // REZ
  72.  
  73.     //-------------------------------------- EX 2 --------------------------------------
  74.     printf("\n\n\n\n------------------ EX 2 -------------------\n");
  75.     int p_value = 0;
  76.  
  77. #pragma omp parallel
  78.     {
  79. #pragma omp sections
  80.         {
  81. #pragma omp section
  82.             {
  83.                 f(&p_value, 100000);
  84.             }
  85. #pragma omp section
  86.             {
  87.                 g(&p_value, 100000);
  88.             }
  89.         }
  90.     }
  91.  
  92.     printf("P value is %d", p_value);
  93. }
Add Comment
Please, Sign In to add comment