On Sun, Aug 17, 2008 at 1:25 AM, David Abrahams
on Sat Aug 16 2008, "Eduardo Panisset"
http://eduardo.panisset-at-gmail.com/> wrote: On Sat, Aug 16, 2008 at 9:32 PM, David Abrahams
wrote: on Sat Aug 16 2008, "Eduardo Panisset" < eduardo.panisset-AT-gmail.com http://eduardo.panisset-at-gmail.com/> wrote:
> There are two threads, each one with its own shared_ptr. Thread 2 created > its shared_ptr2 by copying the shared_prt1 of thread 1. Then the reference > count is equal to 2. > Some time later, shared_ptr1 goes out of scope and then shared_prt2 also > goes out of scope. > Consider the following event sequence: > > 1. Thread 1 executes release member function, and it is preempted before > executing comparation if (new_use_count == 0) > 2. Thread 2 executes release member function until the end, disposing the > pointee. > 3. Thread 1 is rescheduled, executes comparation if (new_use_count == 0) and > also diposes the pointee! > > Is it possible, isn't it?
No. Thread 1 will see new_use_count == 1, thread 2 will see new_use_count == 0 and dispose the pointee, and thread 1 will continue off the end of the function without disposing it.
Ok, David !!! new_use_count is a local variable that receives the ref count inside the critical region synchronizing the shared variable use_count_, so there is no race condition.
There is still a doubt left. How can I copy a shared_ptr from a different thread that has created it and guarantee that the pointee did not go away (race condition between function members release and add_ref_lock ) ?
You make the copy of the shared_ptr in the first thread:
void thread2(shared_ptr<X> q) { ... }
void main_thread(shared_ptr<X> p) { boost::thread t( boost::bind(thread2, p) // <= _copies_ p into the thread function object ); }
Ok David, I understand now. Thank you, very much !