// // compile with // g++ -std=c++0x -pthread -O2 -o TaskThreadPrime TaskThreadPrime.cpp // #include #include #include #include #include using namespace std; class PrimeTask { // Klasse fuer Primzahlzaehlen private: void InitPrimes(); // init ref primes int findPrimes( long start, long end, vector & pvec); vector m_primeRef; // ref prime list vector< vector< long > > m_primeOut; // container for primes int m_task; // task counter int m_nt; // total number of tasks static const long IFIRST = 3; static const long INTERV_LEN = 1000000; static const long PRIME_MAX = 100000000; //static const long PRIME_MAX = 20000000; public: PrimeTask(); int getNPrimes() { int count = 0; for ( unsigned int i=0; i p ) { // found prime m_primeRef.push_back(p); // append to list } } } int PrimeTask::findPrimes( long start, long end, vector & pvec) { // check 1st we have enough ref-primes int ind = m_primeRef.size() - 1; if ( m_primeRef[ind] * m_primeRef[ind] < end ) { cout << "Error, not enough ref-primes " << m_primeRef[ind] << " " << end << endl; return -1; } int npr = 0; for ( long p = start; p < end; p+=2 ) { int index = 0; long t = m_primeRef[index]; // take only primes to test while (t*t <= p) { // and only those smaller sqrt(p) if ( p % t == 0 ) { // not prime, give up break; } index ++; t = m_primeRef[index]; } if (t*t > p ) { // found prime pvec.push_back(p); // append to list npr ++; } } return(npr); } int PrimeTask::runTask ( int itsk ) { if ( itsk >= m_nt ) return( -1 ); long start = INTERV_LEN * itsk + IFIRST; long end = start + INTERV_LEN; int npr = findPrimes( start, end, m_primeOut[itsk]); std::cout << " Executed task " << itsk << " found " << npr << " primes " << std::endl; return(npr); } int main() { PrimeTask tp; int ntsk = tp.getNTasks(); vector> vf; // launch tasks and store for ( unsigned int i=0; i