Thread: std::thread leads to Abort

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Password:
    Join Date
    Dec 2009
    Location
    NC
    Posts
    587

    std::thread leads to Abort

    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.

    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;
    }
    The error:
    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
    Last edited by User Name:; 06-02-2011 at 12:11 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Weird typo leads to interesting result... what does it mean?
    By pollypocket4eva in forum C++ Programming
    Replies: 4
    Last Post: 06-17-2010, 03:30 AM
  2. abort() causes a segfault
    By JFonseka in forum C Programming
    Replies: 12
    Last Post: 04-16-2008, 01:40 AM
  3. abort()
    By swgh in forum C++ Programming
    Replies: 5
    Last Post: 02-22-2008, 04:11 AM
  4. Abort Procedure
    By incognito in forum Windows Programming
    Replies: 5
    Last Post: 01-02-2004, 09:49 PM
  5. Western society leads to unsatisfaction
    By Zewu in forum A Brief History of Cprogramming.com
    Replies: 20
    Last Post: 08-06-2003, 03:45 PM