|
Boost Users : |
Subject: Re: [Boost-users] Passing reference params to boost::thread, parameter copies.
From: OvermindDL1 (overminddl1_at_[hidden])
Date: 2009-09-25 11:54:17
On Fri, Sep 25, 2009 at 7:43 AM, Roman Perepelitsa
<roman.perepelitsa_at_[hidden]> wrote:
> 2009/9/25 Jason Cipriani <jason.cipriani_at_[hidden]>
>>
>> At the end of this message is a test program that uses boost::thread
>> to create two threads. The first is one that takes a parameter by
>> value, the second takes a parameter by reference. I have a couple of
>> questions about some behavior here:
>>
>> 1) When passing by value, why are so many copies of the data made? The
>> program output indicates that there are 9 (!) objects created (at most
>> 5 exist simultaneously), when ideally there would be only 2 (the
>> original and the copy passed to the thread).
>
> That's common for generic boost libraries. If you care about the number of
> copies made, create your own function object that uses reference counting or
> something similar to hold an argument.
> struct runner {
> Â Â runner(const test& t) : arg_(new test(t)) {}
> Â Â void operator()() const {
> Â Â Â expected_nocopy(*arg_);
> Â Â }
> Â Â boost::shared_ptr<test> arg_;
> };
> test t;
> runner r(t);
> boost::thread thr(r);
> By the way, there is no point in accepting argument by value, unless you
> want to modify it. Since your function expected_copy does not modify its
> argument, it's better to change pass-by-value to pass-by-const-ref.
>>
>> 2) When passing by reference, why is the data being copied? The
>> copying behavior when passed by reference is identical to when the
>> param is passed by value (9 objects created, 5 simultaneously). Also,
>> and this isn't shown in the program below, but I would therefore
>> expect the program to crash if the boost::thread outlived the
>> referenced object (of course, it does not, since the object is
>> copied).
>
> Use boost::cref to pass by reference.
> boost::thread thr(expected_nocopy, boost::cref(t));
> Roman Perepelitsa.
You can also use Boost.Phoenix (a replacement for Boost.Bind and
Boost.Lambda that still does even more). Wrapping the things with
ref() will send the pointer along so no copies are ever made.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net