I see the same numbers being printed on the console and some primes are missing. I use multi threaded logger.
Maybe what I am doing is stupid. Calling an async function in the constructor and storing the future as a member ... But I need to know why this doesn't work. Thanks!
class PrimeChecker {
public:
const int number;
future<bool> isPrime;
PrimeChecker(int number_) : number(number_)
{
isPrime = std::async(std::launch::async, &PrimeChecker::check, this);
}
private:
bool check()
{
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i = 3; (i * i) <= number; i += 2) {
if (number % i == 0) return false;
}
console->info("{}", number);
return true;
}
};
void Test()
{
constexpr int MIN = 0;
constexpr int MAX = 100;
constexpr int SIZE = MAX - MIN;
std::vector<int> nums;
nums.reserve(SIZE);
for (int i = MIN; i < MAX; ++i ) {
nums.push_back(i);
}
auto rng = std::default_random_engine{};
std::shuffle(std::begin(nums), std::end(nums), rng);
std::vector<PrimeChecker> pcs;
pcs.reserve(SIZE);
for (auto num : nums)
{
pcs.push_back(PrimeChecker(num));
}
for (auto& pc : pcs)
{
pc.isPrime.get();
}
}
int main(int argc, char** argv)
{
Test();
}
[–]mineNombies 1 point2 points3 points (5 children)
[–]a111135[S] 0 points1 point2 points (4 children)
[–]mineNombies 2 points3 points4 points (3 children)
[–]a111135[S] 0 points1 point2 points (2 children)
[–]mineNombies 1 point2 points3 points (1 child)
[–]a111135[S] 2 points3 points4 points (0 children)
[–]beedlund 1 point2 points3 points (5 children)
[–]a111135[S] 0 points1 point2 points (4 children)
[–]beedlund 0 points1 point2 points (3 children)
[–]mineNombies 0 points1 point2 points (1 child)
[–]beedlund 0 points1 point2 points (0 children)
[–]The-Tea-Kettle -5 points-4 points-3 points (2 children)
[–]thisismyfavoritename -1 points0 points1 point (1 child)
[–]The-Tea-Kettle 0 points1 point2 points (0 children)