c++ - Sum of all primes under 2 million with threads giving incorrect answer -


so code gets primes correctly , gives result 142,913,828,922.

loop summing primes

for (int = 2; < 2000001; i++){         if (isprime(i)){             sum += i;         }     } 

but when trying create initially, decided try distribute tasks threads run faster , came this:

in main:

thread first(threadf, 2, 1000001, std::ref(sum)); thread second(threadf, 1000000, 1750001, std::ref(sum)); thread third(threadf, 1750000, 1900001, std::ref(sum)); thread fourth(threadf, 1900000, 2000001, std::ref(sum)); first.join(); second.join(); third.join(); fourth.join(); 

with threadf being

void threadf(int lowerbound, int upperbound, unsigned long long int &sum){ (lowerbound; lowerbound < upperbound; lowerbound++){     if (isprime(lowerbound)){         sum += lowerbound;         cout << "prime" << lowerbound << endl;     } }} 

i kinda split them thinking higher numbers take longer didn't math determine how should split them. problem when use threads, don't consistent answer. every time, i've gotten close other method's solution, never exact , answers aren't same. they're off few million or so. doing learn bit threads , while solving eulers project problem not practical reason.

you program has data race sum. , have 3 options, first use of atomic types of variables, , second, using thread-local variables.or use different var name sum0,1.. when thread run over,sum them together.

if use c++11,atomic or thread_local maybe meet need.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -