reference counted class and multithreading

前端 未结 2 682
梦如初夏
梦如初夏 2021-01-21 17:29

I \'m a novice in multithreading programing and i have still confusion with that.

Below is my reference counted class:

class Rbuffer
{
  private:
    cha         


        
2条回答
  •  花落未央
    2021-01-21 18:14

    Your analysis isn't right; The code you posted is using interlockedDecrement correctly.

    This is a safe use

     if(InterlockedDecrement(&mRefCount)==0)
               cleanup();
    

    .. but this would indeed have the problem you described

     InterlockedDecrement(&mRefCount);
    
     if (mRefCount==0)
               cleanup();
    

    However, the use of delete this is much more likely to be the cause of the problem. It's very unlikely you're passing the 'absolutely positively 100% sure' tests described here: http://www.parashift.com/c++-faq-lite/delete-this.html

    In particular, the following simple code would cause chaos.

    {
      RBuffer x;  // count is what... ? zero
      x.incRef(); // make count one
      x.decRef(); // make count zero, and deletes itself 
    }  // now x goes out of scope, so destructor is called a second time = chaos! 
    

    A normal "reference counting" idiom involves a 'shared object' (with the count), and simple 'reference objects' (not C++ references, although the semantics would be similar) which refer to the shared object. The constructors and destructors of the 'reference objects' are responsible for calling the incref/decref methods on the shared object. So the shared object is automatically counting the number of active 'reference objects'.

提交回复
热议问题