Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <thread>
- #include <mutex>
- using namespace std;
- struct PrimeResult
- {
- int value;
- };
- mutex primeVectorMutex;
- std::vector<PrimeResult> primes;
- std::vector<PrimeResult> non_primes;
- bool test_if_prime(int i)
- {
- for (int j = 2; j <= i / 2; j++)
- if (!(i % j))
- return false;
- return true;
- }
- void evaluate_primes(int begin, int end)
- {
- for (int i = begin; i < end; i++)
- {
- bool isPrime = test_if_prime(i);
- primeVectorMutex.lock();
- if (isPrime)
- primes.push_back({ i });
- else
- non_primes.push_back({ i });
- primeVectorMutex.unlock();
- }
- }
- void print_results()
- {
- for (auto& result : primes)
- {
- cout << "Prime found: " << result.value << endl;
- }
- }
- int primesToFind = 100000000;
- int main()
- {
- thread thread_1(evaluate_primes, 1, primesToFind / 2);
- thread thread_2(evaluate_primes, primesToFind / 2, primesToFind);
- thread_1.join();
- thread_2.join();
- print_results();
- while (true)
- {
- ;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement