I \'m a novice in multithreading programing and i have still confusion with that.
Below is my reference counted class:
class Rbuffer
{
private:
cha
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'.