|
Boost Users : |
Subject: [Boost-users] Using Boost.Atomic for thread-safe reference counting with strong exception guarantee
From: Narcoleptic Electron (narcoleptic.electron_at_[hidden])
Date: 2010-03-08 16:38:29
I'm trying to create a thread-safe, strong-exception-guaranteed
"intrusive_pte" (intrusive pointee) class that represents a drop-in
reference-counted base class for a pointee of intrusive_ptr. I'm
using the pending Boost.Atomic library
(http://www.chaoticmind.net/~hcb/projects/boost.atomic/) and am basing
my code on the example given
(http://www.chaoticmind.net/~hcb/projects/boost.atomic/doc/atomic/usage_examples.html#boost_atomic.usage_examples.example_reference_counters),
but not yet having a sound understanding of memory barriers, I am
unsure if my code for the overflow exception is correct or ideal.
The relevant code snippet is below. Any feedback would be greatly appreciated.
Thanks!
--- mutable atomic< IntegralType > ref_count; mutable mutex add_ref_mutex; void add_ref() const { mutex::scoped_lock add_ref_lock( add_ref_mutex ); if ( integer_traits< IntegralType >::const_max == ref_count.load( memory_order_relaxed ) ) { throw_exception( std::overflow_error( "Reference count overflow." ) ); } ref_count.fetch_add( 1, memory_order_relaxed ); } friend void intrusive_ptr_add_ref ( intrusive_pte const * const p ) { BOOST_ASSERT( p && "The argument cannot be null." ); p->add_ref(); } friend void intrusive_ptr_release ( intrusive_pte * const p ) { BOOST_ASSERT( p && "The argument cannot be null." ); BOOST_ASSERT( ( 0 < p->ref_count.load( memory_order_acquire ) ) && "Reference count underflow." ); if ( p->ref_count.fetch_sub( 1, memory_order_release ) == 1 ) { atomic_thread_fence( memory_order_acquire ); checked_delete( p ); } }
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