简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM