I'm trying to code a program for dealing with prime numbers. The idea is to have the prime list readable by all threads, but writeable by 1.
The error:Code:#include "gmpxx.h" #include <iostream> #include <thread> #include <vector> // primes must be initialised with at least the first two prime numbers. static std::vector<mpz_class> primes = {2, 3}; // integer sqrt static mpz_class sqrt(mpz_class n) { mpf_class x, y = n; do{ x = y; y = (x + n / x) / 2; }while(abs(y - x) >= 1); return y; } // extends primes to the lowest prime greater than or equal to n static void extend_primes(mpz_class n) { // Unfortunately, the primes can't efficiently, if at all, be extended concurrently... static std::mutex m; std::lock_guard<std::mutex> lock(m); for(mpz_class i = primes.back() + 2;i <= n;i += 2) { bool prime = true; // Assume i is prime. for(auto j = primes.begin();prime && *j <= sqrt(i);j++) if(i % *j == 0) prime = false; if(prime) primes.push_back(i); } } int main() { extend_primes(7); std::thread t(extend_primes, 19); // This (or a resulting call) must be the cause. When commented out, everything works fine. for(auto i = primes.begin();i < primes.end();i++) std::cout << i->get_str() << " "; std::cout << std::endl; return 0; }
Code:$ gcc -ggdb -std=c++0x -lstdc++ -lgmp -o prime prime.cpp $ ./prime terminate called after throwing an instance of 'std::system_error' what(): Aborted



2Likes
LinkBack URL
About LinkBacks



