mercredi 26 décembre 2018

Expression does not evaluate to a constant

I am trying to write a multi-threaded program to run the sieve to Eratosthenes algorithm for a given set of numbers, with options to print the primes found, and to compare the execution time from different threads used. This is part of a university course. I am using C++11 threads with the default visual studio compiler. At present, I am having problems getting a build, I suspect due to the way I am trying to handle the threads. Here is what I have so far in the Eratosthenes function:

int Eratosthenes(int input)
{
    bool pFlag[input + 1];
    memset(pFlag, true, sizeof(pFlag));

    for (int pTest = 2; pTest*pTest <= input; pTest++)
    {
        if (pFlag[pTest] == false)                              // If prime[p] is not changed, then it is a prime
        {
            for (int i = pTest * 2; i <= input; i += pTest)     // Update all multiples of p
                pFlag[i] = false;
        }
    }

    for (int i = 2; i <= i; i++)                            //print all primes
    {
        if (pFlag[i] == true)
            cout << i << " ";
    }

}

And in the main I am calling some helper functions which get user input on the number of threads, and the maximum number to search for primes.

int main()
{
    int MaxT = getThreads();
    int maxN = getMaxN();
    Counter counter;
    vector<thread> threads;

    for (int i = 0; i < MaxT; i++)
    {
        threads.push_back(thread(Eratosthenes(counter.Value)));
        counter.increment();
    }
    for (auto& thread : threads)
    {
        thread.join();
    }
    counter.Value = 0;
    system("pause");
}

I have also created a structure to handle the incrementing and mutex list.

struct Counter
{
    int Value=0;
    mutex mtx;
    void increment()
    {
        mtx.lock();
        ++Value;
        mtx.unlock();
    }
};

So far, all errors appear related to the use of input in the Eratosthenes function, with the first being that it does not evaluate to constant, with a note afterwards saying that this was caused by a read of a variable outside of its lifetime. A second possibly related error in the same section states that with relation to the line pFlag[i] = false; the array type 'bool[input+]' is not assignable.

Thanks for your assistance :)

Aucun commentaire:

Enregistrer un commentaire