|
Boost : |
Subject: Re: [boost] Using Boost.Atomic for shared_ptr
From: Helge Bahmann (hcb_at_[hidden])
Date: 2009-12-20 19:00:32
Am Sunday 20 December 2009 20:16:03 schrieb Phil Endecott:
> Dear All,
>
> I have just had a quick look at how easily shared_ptr could be adapted
> to use Helge's proposed Boost.Atomic. To me it looks very simple, but
> maybe someone who knows more about all this could have a look? I took
> the non-threaded implementation in sp_counted_base_nt.hpp as a starting
> point, and simply changed the two counts from long to
> boost::atomic<long> :
>
> boost::atomic<long> use_count_; // #shared
> boost::atomic<long> weak_count_; // #weak + (#shared != 0)
wouldn't "int" do?
> Then, the majority of the methods don't need to change since the atomic
> template provides atomic versions of e.g. operator++. The one that
> does need more work is add_ref_lock, which I've implemented as follows:
>
> bool add_ref_lock() // true on success
> {
> while (1) {
> long c = use_count_;
> if (c == 0) return false;
> if (use_count_.compare_exchange_weak(c,c+1)) return true;
> }
> }
I would suggest:
bool add_ref_lock() // true on success
{
long c = use_count_.load(memory_order_relaxed);
do {
if (c == 0) return false;
} while(!use_count_.compare_exchange_weak(c, c+1,
memory_order_relaxed));
return true;
}
I have the nagging thought in my mind that the last one must
be "memory_order_acquire" but I am too tired to really convince me either
way :(
> There is also the question of memory barriers. I understand that
> things like operator++ provide the most pessimistic memory barriers, so
> ideally these should be replaced with calls that use the right barriers.
I have some code in the "examples" section on this topic:
> Does anyone have any thoughts about how this would compare with the
> current custom assembler implementations?
For ppc and x86 it should end up mostly the same (not always same
instructions, but the same effect both in functionality and performance),
have not yet looked at the others.
Best regards,
Helge
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk