mercredi 28 décembre 2016

C++ Using threadpool for a task with arguments

I was looking at this question and I was wondering how I can convert the following program into a thread pool.

This program is searching for twin-prime numbers. I like to break the searching range between threads for faster searching. How can I do it?

One problem is that want to call twin_range at each thread. However, it requires arguments and schedule function does not accept argument for the function. In addition, this function affects the global variable twin_primes which is at the risk of multiple access. How to solve this problem too?

I also don't care about the order of the results.

Any <thread> or <boost/thread.hpp> based solution is welcome.

#include <string>
#include <iostream>
#include <vector>

std::vector<long> twin_primes;

bool is_prime(long a)
{
    if(a<2l)
        return false;
    if(a==2l)
        return true;
    for(long i=2;i*i<=a;i++)
        if(a%i==0)
            return false;
    return true;
}

void twin_range(long l1,long l2)
{
    for(long l=l1;l<=l2;l++)
        if(is_prime(l) && is_prime(l+2))
            twin_primes.push_back(l);
}

int main()
{

    twin_range(10000000l,20000000l);

    for(long l:twin_primes)
    {
        std::cout
            <<l<<" and "<<(l+2)
            <<" are twin prime numbers."
            << std::endl;
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire