jeudi 1 décembre 2016

Segmentation fault using array of promises

I've written multithreading program, using promises and futures to check whether given number is prime. The correctness or efficiency of this program is not a point, but fact of the segmentation error which occurs in every execution - I had similar problem with more complex program, so I've written this simple one to understand it, and the error is still here. Maybe I don't understand something about concurrency, or promises/futures, but I think that everything is done here in proper way... Can anybody explain why it's not working? It would be very helpful :)

Here's the code:

#include <future>
#include <thread>
#include <iostream>
#include <initializer_list>
#include <vector>
#include <cassert>


namespace {
const int THREADS_NUMBER = 8;

void f(int n, std::vector<int>& divisiors, std::promise<bool>& isPossiblePrime) {
    bool isPrimeCandidate = true;
    for (auto i : divisiors)
        if (n % i == 0) {
            isPrimeCandidate = false;
            break;
        }
    isPossiblePrime.set_value(isPrimeCandidate);
}


}

int main() {
    int n;
    std::cin >> n;
    assert(n > 2);
    std::promise<bool> promises[THREADS_NUMBER];
    std::future<bool> futures[THREADS_NUMBER];
    for (int i = 0; i < n; i++)
        futures[i] = promises[i].get_future();
    std::thread threads[THREADS_NUMBER];

    std::vector<int> divisiors[THREADS_NUMBER];
    for (int i = 2; i < n; i++)
        divisiors[i % THREADS_NUMBER].push_back(i);

    for (int i = 0; i < THREADS_NUMBER; i++) 
        threads[i] = std::thread{ [&]() { f(n, divisiors[i], promises[i]); }};

    bool isPrime = true;
    for(auto & f : futures) {
        bool out = f.get();
        isPrime = out && isPrime;
    }

    for (auto& t : threads)
        t.join();

    if(isPrime) std::cout << "PRIME" << std::endl;
    else std::cout << "NOT PRIME" << std::endl;

}

I compile with g++ -std=c++11 -Wall -lpthread on Linux.

Aucun commentaire:

Enregistrer un commentaire