Skip to content

Instantly share code, notes, and snippets.

@bazhenovc
Created December 3, 2015 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bazhenovc/77c57cf41bfcee32eebf to your computer and use it in GitHub Desktop.
Save bazhenovc/77c57cf41bfcee32eebf to your computer and use it in GitHub Desktop.
/// Increase the reference count on the object.
template< class T, class DeletePolicy >
inline void ThreadSafeRefCount< T, DeletePolicy >::addRef()
{
dFetchAndAdd( mRefCount, 2 );
}
/// Decrease the object's reference count and delete the object, if the count
/// drops to zero and claiming the object by the current thread succeeds.
template< class T, class DeletePolicy >
inline void ThreadSafeRefCount< T, DeletePolicy >::release()
{
AssertFatal( mRefCount != 0, "ThreadSafeRefCount::release() - refcount of zero" );
if( decrementAndTestAndSet( mRefCount ) != 0 )
DeletePolicy::destroy( ( T* ) this );
}
/// Decrement the given reference count. Return 1 if the count dropped to zero
/// and the claim bit has been successfully set; return 0 otherwise.
template< class T, class DeletePolicy >
U32 ThreadSafeRefCount< T, DeletePolicy >::decrementAndTestAndSet( U32& refCount )
{
U32 oldVal;
U32 newVal;
do
{
oldVal = refCount;
newVal = oldVal - 2;
AssertFatal( oldVal >= 2,
"ThreadSafeRefCount::decrementAndTestAndSet() - invalid refcount" );
if( newVal == 0 )
newVal = 1;
}
while( !dCompareAndSwap( refCount, oldVal, newVal ) );
return ( ( oldVal - newVal ) & 1 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment