Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::thread - Simple example doesn't work (C++)

To get started with boost::thread, I've written a very simple example -- which doesn't work. Could anyone point out my mistake?

I wrote a very simple functor-type class to do the work. It's supposed to compute the sum of an std::vector of doubles, and give me a way to get the result later:

class SumWorker
{
private:
    double _sum;
public:

    SumWorker() : _sum(-1.0) {}

    void operator() (std::vector<double> const & arr)
    {
        _sum = 0.0;
        for(std::vector<double>::const_iterator i = arr.begin();
            i != arr.end();
            i++)
        {
            _sum += (*i);
        }
    }

    double const value() const
    {
        return _sum;
    }
};

Now, I can compute the sum in one of two ways. If I do it within the main thread, like,

SumWorker S;
S(numbers);              // "numbers" is an std::vector<double>
double sum = S.value();  // "sum" now contains the sum

then everything works. However, if I try to do this in a separate thread (which was the whole point),

SumWorker S;
boost::thread thread(S, numbers); // Should be equivalent to "S(numbers);"
thread.join();                    // Wait for thread to finish
double sum = S.value();           // "sum" now contains -1.0

...then it doesn't work.

Sorry if this is obvious, but I'm stumped. Any clues?

like image 407
user1889797 Avatar asked May 16 '13 14:05

user1889797


2 Answers

You should use

boost::thread thread(boost::ref(S), boost::cref(numbers));

since by default thread copies these arguments.

like image 184
ForEveR Avatar answered Nov 01 '22 14:11

ForEveR


Your SumWorker object S is being copied by the thread constructor therefore its member is never updated.

http://www.boost.org/doc/libs/1_53_0/doc/html/thread/thread_management.html#thread.thread_management.thread.callable_constructor

like image 43
TractorPulledPork Avatar answered Nov 01 '22 14:11

TractorPulledPork