Note that there are some explanatory texts on larger screens.

plurals
  1. POAtomicness of copy constructor of reference count object using InterlockedIncrement64
    text
    copied!<p>I'm trying to wrap my head around how I can ensure that an objects reference count is thread safe.</p> <pre><code>class MyObject{ //Other implementation details private: mutable volatile LONGLONG * m_count; IData * m_data; }; </code></pre> <p>Assume the necessary class declaration are there, just keeping it simple. Here is the implementation of the copy constructor and destructor.</p> <pre><code>MyObject::MyObject(const MyObject&amp; rhs) : m_count(rhs.m_count), m_data(rhs.m_data){ InterlockedIncrement64(m_count); } MyObject::~MyObject(){ if(InterlockedDecrement64(m_count) == 0) delete m_data; } </code></pre> <p>Is this thread safe? How is the intilization list of the copy constructor seen, atomic or not? Does that even matter? Should I be setting the incremented value of the count in the initilization list (is this possible)?</p> <p>As it stands is this good enough. I'm thinking it is, otherwise, how could I get into a scenario where <code>thread1</code> is copying and <code>thread2</code> is destroying concurrently when the <code>count == 1</code>. There has to be a handshake between the threads, meaning thread1 has to copy the object entirely before thread2's object goes out of scope correct?</p> <p>After reading some of these responses I went back and did a little research. Boost implements their shared_ptr very similiarly. Here is the destructor call.</p> <pre><code>void release() // nothrow { if( BOOST_INTERLOCKED_DECREMENT( &amp;use_count_ ) == 0 ) { dispose(); weak_release(); } } </code></pre> <p>Some have suggested that in the boost documentation that it clearly states assignment is not thread safe. I agree and disagree. I think in my case I disagree. I only need the handshake between threadA and threadB. I don't think some of the problems described in some of the replies apply here (although they were eye opening replies that I did not completely think through).</p> <p>Example ThreadA atach(SharedObject); //Shared object passed by value, count incremented etc etc.</p> <p>ThreadB //Accepts the object, adds it to a list of shared objects. ThreadB is on a timer that notifies all SharedObjects of an event. Before Notifying, a copy of the list is made protected by a critical section. The CS is released, the copies are notified.</p> <p>ThreadA detach(SharedObject); //Removes the shared object from the list of objects</p> <p>Now, concurrently ThreadB is singaling the SharedOjbect and already made a copy of the list before ThreadA detached said shared object. Everything is ok no?</p>
 

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