Boost logo

Boost Users :

From: Jonathan Biggar (jon_at_[hidden])
Date: 2007-08-06 12:08:08


Ovanes Markarian wrote:
>>>> void g(boost::shared_ptr<const B> ptr)
>>> {
>>> //...
>>> }
>>>
>>> void f()
>>> {
>>> boost::shared_ptr<const B> ptr(new B);
>>>
>>> //give ptr to threads
>>> boost::thread thrd1(boost::bind(&g, ptr));
>>> boost::thread thrd2(boost::bind(&g, ptr));
>>>
>>> //fire and forget
>>> ptr.reset();
>>> }
>> This example is OK. You have three distinct shared_ptr variables, all named
>> 'ptr' (one per thread). Despite them having the same name, they are still
>> different objects, not shared among threads, so you can assign/reset/destroy
>> them at will.
>
> Yes, just in addition, your code would be broken, if g would expect a shared_ptr by reference,
> i.e. void g(boost::shared_ptr<const B>& ptr). Then all your threads would own the same shared_ptr
> instance and the thread in which runs the function f would reset the pointer which might be used
> by thrd1 or thrd2 and that might cause the scenario from the docs example.

I wouldn't think so in this case, since boost::bind makes a copy of the
shared_ptr before it gets passed to g(). If the code used
boost::bind(&g, boost::ref(ptr)), then there would be a race condition.

-- 
Jon Biggar
Floorboard Software
jon_at_[hidden]
jon_at_[hidden]
ra

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