I 'm a novice in multithreading programing and i have still confusion with that.
Below is my reference counted class:
class Rbuffer
{
private:
char *m_pnData;
volatile unsigned int mRefCount;
public:
Rbuffer(int nLength) : mRefCount(0)
{
m_pnData = new char[nLength];
}
~Rbuffer(){
delete[] m_pnData;
}
void decRef() {
if(InterlockedDecrement(&mRefCount)==0){
delete (Rbuffer *)this;
}
}
void incRef() {
InterlockedIncrement(&mRefCount);
}
};
is it fully thread safe? Can you exclude this situation:
ThreadA ThreadB
PointerToRBuffer->incRef();//mRefCount 1
switch->
PointerToRBuffer->incRef();//mRefCount 2
<-switch
PointerToRBuffer->decRef();
InterlockedDecrement(&mRefCount)//mRefCount 1
switch->
PointerToRBuffer->decRef();//mRefCount 0!
InterlockedDecrement(&mRefCount);
if (0==0)
delete (Rbuffer *)this;
<-switch
if (0==0)
//deleting object, that doesn't exist
delete (Rbuffer *)this;
//CRASH
The reasons of crashing could be that only (InterlockedDecrement(&mRefCount)) part is atomic, but if (InterlockedDecrement(&mRefCount)==0) not? Am i wrong with example above?
Thanks in advance for your opinions and advice to make my class fully thread safe.
delete[] m_pnData) and making no affordances for protecting construction of a class who's instances can literally self-destruct (i.e. a static class factory method with a private constructor family). That said, I think your crash may have nothing to do with reference counting. Frankly, the fixed-casts on thedeleteoperands should be equally concerning. I assume there is some reason you're not usingstd::shared_ptr<Rbuffer>for this, as that would make all of this irrelevant.