I'm using boost::thread to add number from 0 to 1,000,000,000. I split the thread into adding odd numbers and even numbers.
Code:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/cstdint.hpp>
#include <boost/thread.hpp>
#include <iostream>
class Test
{
private:
int even_odd;
boost::uint64_t sum ;
public:
Test(int what , int s = 0): even_odd(what) , sum(s) {};
void operator() ()
{
for (int i = even_odd; i < 100000; i += 2)
sum += i;
std::cout << sum << std::endl;
}
boost::uint64_t operator+(const Test & Second) const
{
std::cout << sum << std::endl;
std::cout << Second.sum << std::endl;
return sum + Second.sum;
}
void print()
{
std::cout << sum << std::endl;
}
};
int main()
{
boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time(); // start calculating time
Test even(0); // add even numbers;
Test odd(1); // add odd numbers
boost::thread t1(even); //start adding even
boost::thread t2(odd); //start adding odd
t1.join(); //put main to sleep
t2.join(); //put main to sleep
boost::uint64_t sum = even + odd;
boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time();
std::cout << end - start << std::endl;
std::cout << "The sum of number from 0 to 1000000000 is " << sum << std::endl;
return 0;
}
The sum is keep coming up to be zero. I realize that because boost::thread() creates a copy of the class instead. Is there away to obtain return value from a thread?