Boost logo

Boost Users :

Subject: Re: [Boost-users] [Boost.Smart_ptr] global_reset (revamp) for shared_ptr
From: Andrew Holden (aholden_at_[hidden])
Date: 2009-08-19 09:39:07


John Dlugosz wrote on Tuesday, August 18, 2009 2:47 PM:
>> PROBLEM
>>
>> I recently needed a 'shared_ptr' that could be globally reset -- that
>> is, any one of the owners of the controlled resource could
unilaterally
>> replace that resource for the benefit (perhaps) of everyone else.
>>
>
>
> The replacement has to be able to deal with code that is in the
process of
> using another smart pointer to the original object.
>
> I would solve this by having uses mark their in-use scope by simply
> fetching a local copy.
>
> That is, consider the explicit usage protocol:
>
> shared_ptr<mytype> global;
>
> to use:
> shared_ptr<mytype> local= global; // (A)
> local->foo();
> // let local go out of scope
>
> to update:
> global= newvalue; // (B)
>
>
> Table a couple threading issues for the moment.
> I'd think of an approach that automated the "use" by having an
operator->
> that returned a shared_ptr.
> And, encapsulate the update step as a member function as well, so any
needed
> locking or added steps can be accommodated.
>
> Back to the issues: I don't recall whether the shared_ptr
documentation is
> clear as to whether multiple threads can issue (A) at the same time.
> Multiple threads executing (B) is not allowed. And whether (A) with
one (B)
> can occur at the same time is probably related to multiple (A)'s, and
> certainly not specified in the standard.

The threading issues are addressed at
http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr.htm#Threa
dSafety

To summarize, there is no limit on the number of line A that can happen
at any one time, but line B must have exclusive access to global.

Ideally, you should have a reader-writer mutex to guard global. Lock it
for read access (non-exclusive) for line A and unlock it before
"local->foo()". Lock it for write access (exclusive) for line B.

If you do not have a reader-writer mutex, then use an ordinary mutex to
lock both line A and line B. This may, however hurt concurrency if line
A is run frequently.

Note that since I am not suggesting to use this mutex to lock
"local->foo()", this in no way affects mytype's thread safety for good
or ill.


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