Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "is_prime.h"
- #include <cmath>
- #include <algorithm>
- #include <thread>
- #include <atomic>
- #include <vector>
- #include <iostream>
- void CheckFunc(uint64_t x, std::atomic<uint64_t>& i, std::atomic<bool>& result) {
- result.store(x % i != 0);
- i.fetch_add(1);
- }
- void CloseAllThreads(std::vector<std::thread>& threads) {
- for (auto& this_thread : threads) {
- if (this_thread.joinable()) {
- this_thread.join();
- }
- }
- }
- bool IsPrime(uint64_t x) {
- if (x <= 1) {
- return false;
- }
- uint64_t root = sqrt(x);
- auto bound = std::min(root + 6, x);
- std::atomic<uint64_t> i = 2ull;
- std::atomic<bool> result = true;
- std::vector<std::thread> threads(10);
- while (i.load() < bound && result.load()) {
- for (auto &this_thread : threads) {
- if (i.load() < bound) {
- this_thread = std::thread(CheckFunc, x, std::ref(i), std::ref(result));
- } else {
- break;
- }
- if (!result.load()) {
- CloseAllThreads(threads);
- break;
- }
- }
- }
- CloseAllThreads(threads);
- std::cout << x << " - " << i.load() << "... " << result.load() << std::endl;
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement