Using Boost.Atomic for thread-safe reference counting with strong exception guarantee
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_examp...), 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 ); } }
participants (1)
-
Narcoleptic Electron