Advertisement
Guest User

Untitled

a guest
Oct 17th, 2015
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <thread>
  4. #include <mutex>
  5.  
  6. using namespace std;
  7.  
  8. struct PrimeResult
  9. {
  10.     int value;
  11. };
  12.  
  13. mutex primeVectorMutex;
  14. std::vector<PrimeResult> primes;
  15. std::vector<PrimeResult> non_primes;
  16.  
  17. bool test_if_prime(int i)
  18. {
  19.     for (int j = 2; j <= i / 2; j++)
  20.         if (!(i % j))
  21.             return false;
  22.  
  23.     return true;
  24. }
  25.  
  26. void evaluate_primes(int begin, int end)
  27. {
  28.     for (int i = begin; i < end; i++)
  29.     {
  30.         bool isPrime = test_if_prime(i);
  31.  
  32.         primeVectorMutex.lock();
  33.         if (isPrime)
  34.             primes.push_back({ i });
  35.         else
  36.             non_primes.push_back({ i });
  37.         primeVectorMutex.unlock();
  38.     }
  39. }
  40.  
  41. void print_results()
  42. {
  43.     for (auto& result : primes)
  44.     {
  45.         cout << "Prime found: " << result.value << endl;
  46.     }
  47. }
  48.  
  49. int primesToFind = 100000000;
  50.  
  51. int main()
  52. {
  53.     thread thread_1(evaluate_primes, 1, primesToFind / 2);
  54.     thread thread_2(evaluate_primes, primesToFind / 2, primesToFind);
  55.  
  56.     thread_1.join();
  57.     thread_2.join();
  58.  
  59.     print_results();
  60.  
  61.     while (true)
  62.     {
  63.         ;
  64.     }
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement