Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I safely release an object shared between threads using boost::shared_ptr?
    primarykey
    data
    text
    <p>I wonder, is it safe to implement like this? :</p> <pre><code>typedef shared_ptr&lt;Foo&gt; FooPtr; FooPtr *gPtrToFooPtr // global variable // init (before any thread has been created) void init() { gPtrToFooPtr = new FooPtr(new Foo); } // thread A, B, C, ..., K // Once thread Z execute read_and_drop(), // no more call to read() from any thread. // But it is possible even after read_and_drop() has returned, // some thread is still in read() function. void read() { FooPtr a = *gPtrToFooPtr; // do useful things (read only) } // thread Z (executed once) void read_and_drop() { FooPtr b = *gPtrToFooPtr; // do useful things with a (read only) b.reset(); } </code></pre> <p>We do not know which thread would do the actual realease. Does boost's <code>shared_ptr</code> do the release safely under circumstance like this?</p> <p>According to boost's document, thread safety of <code>shared_ptr</code> is:</p> <blockquote> <p>A <code>shared_ptr</code> instance can be "read" (accessed using only const operations) simultaneously by multiple threads. <strong><em>Different</em></strong> <code>shared_ptr</code> instances can be "written to" (accessed using mutable operations such as operator<code>=</code> or <code>reset</code>) simultaneosly by multiple threads.</p> </blockquote> <p>As far as I am concerned, the code above does not violate any of thread safety criteria I mentioned above. And I believe the code should run fine. Does anyone tell me if I am right or wrong?</p> <p>Thanks in advance.</p> <hr> <h2><strong>Editted 2012-06-20 01:00 UTC+9</strong></h2> <p>The pseudo code above works fine. The <code>shared_ptr</code> implementation guarantees to work correctly under circumstances where multiple thread is accessing instances of it (each thread <strong>MUST</strong> access its own instance of <code>shared_ptr</code> instantiated by using <em>copy constructor</em>). </p> <p>Note that in the pseudo code above, you must <code>delete gPtrToFooPtr</code> to have the <code>shared_ptr</code> implementation finally release (drop the reference count by one) the object it owns(not proper expression since it is not an <code>auto_ptr</code>, but who cares ;) ). And in this case, you must be aware of the fact that it may cause SIGSEGV in multithreaded application.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload