On Jun 7, 6:26 am, Yong Sun <
find...@gmail.com> wrote:
> Here is the question I raised on stack-overflow, no reply yet :(
>
>
http://stackoverflow.com/questions/2823512/using-shared-ptr-to-implem...
Hi Yong,
You've came to the right shop :)
It won't work with the current implementation.
Consider:
rcu_const_pointer get_reading_copy ()
{
spin_until_eq (m_is_swapping, 0);
return m_data_ptr;
}
Reader waits for m_is_swapping==0, then reader starts copying the
pointer, and writer simultaneously starts mutating the pointer ->
crash.
// as spin_until_eq does not have memory barrier protection,
// we need to place a read barrier to protect the loading of
// new_data_ptr not to be re-ordered before its construction
Memory barriers is always a game of two. If one thread omits a memory
barrier, there is nothing another thread can do to compensate for
that. Memory barriers must be executed by both threads to get any
effect.
The easiest way to emulate smart pointer with strong thread-safety (a
thread can obtain a reference to an object even if he does not hold a
one yet) is to use shared_ptr+rw_mutex. I.e. When a thread reads the
ptr, he locks the mutex for reading; when a thread writes the ptr, he
locks the mutex for writing.
However both C++0x and boost provide reference counted objects with
strong thread safety. Consult latest boost sources - there are free
standing functions atomic_load/atomic_store/atomic_exchange/
atomic_compare_exchange for shared_ptr.
--
Dmitriy V'jukov