Advertisement
Dewarrum

PosixPrimeNumbers

Dec 15th, 2019
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <iostream>
  3. #include <ctime>
  4. #include <cmath>
  5.  
  6. #pragma comment(lib, "pthreadVCE2.lib")
  7.  
  8. struct parameters_t {
  9.     int start;
  10.     int end;
  11.     int number;
  12.     bool result;
  13. };
  14.  
  15. bool naive() {
  16.     const int number = 499999219;
  17.     int currentDelimiter = 2;
  18.  
  19.     while (currentDelimiter * currentDelimiter < number) {
  20.         if (number % currentDelimiter == 0)
  21.             return false;
  22.  
  23.         currentDelimiter++;
  24.     }
  25.  
  26.     return true;
  27. }
  28.  
  29. auto t = true;
  30. auto f = false;
  31.  
  32. void* routine(void* parameters) {
  33.     auto p = (parameters_t*)parameters;
  34.  
  35.     for (auto i = p->start; i < p->end; i++) {
  36.         if (p->number % i == 0) {
  37.             return (void*)false;
  38.         }
  39.     }
  40.  
  41.     return (void*)true;
  42. }
  43.  
  44. void testParallel() {
  45.     const int threadCount = 4;
  46.     const int number = 499999219;
  47.     auto intervalWidth = (number - 2) / threadCount;
  48.  
  49.     pthread_t* threads = new pthread_t[threadCount];
  50.     auto params = new parameters_t[threadCount];
  51.     auto results = new bool[threadCount];
  52.  
  53.     for (auto i = 0; i < threadCount; i++) {
  54.         params[i] = parameters_t();
  55.         params[i].start = i == 0 ? 2 : i * intervalWidth;
  56.         params[i].end = i == threadCount - 1 ?
  57.             number - 1 : params[i].start + intervalWidth - 1;
  58.         params[i].number = number;
  59.  
  60.         pthread_create(&threads[i], nullptr, routine, &params[i]);
  61.     }
  62.  
  63.     for (auto i = 0; i < threadCount; i++) {
  64.         void* localResult;
  65.         pthread_join(threads[i], &localResult);
  66.         results[i] = (bool)localResult;
  67.         printf("Thread#%d returned %d\n", i, results[i]);
  68.     }
  69.  
  70.     auto result = false;
  71.     for (int i = 0; i < threadCount; i++) {
  72.         result = results || results[i];
  73.     }
  74.  
  75.     printf(result ? "Not Prime" : "Prime");
  76.     printf("\n");
  77. }
  78.  
  79. int main() {
  80.     auto start = clock();
  81.  
  82.     for (auto i = 0; i < 1; i++) {
  83.         testParallel();
  84.         // naive();
  85.     }
  86.  
  87.     auto end = clock();
  88.     auto ms = end - start;
  89.  
  90.     printf("Ellapsed: %ld ms", ms);
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement