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?
You should use
boost::thread thread(boost::ref(S), boost::cref(numbers));
since by default thread copies these arguments.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With