Fixing potential race condition

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
cyr1x
Member
Member
Posts: 207
Joined: Tue Aug 21, 2007 1:41 am
Location: Germany

Fixing potential race condition

Post by cyr1x »

Hi,
I'm currently on the way of implementing the kernel's object manager.
Now there's a problem, I came across.
Object's are reference counted (so they're deleted if not used anymore)
Now I tought of something like this:

Code: Select all

void Reference()
{
    refCount++;
}

void Release()
{
    refCount--;
    if(refCount == 0)
        delete this;
}
So far so good.
Well, now consider a context switch occurs after entering "Reference" and before "refCount++"
and the other context does a "Release". When the count then drops the zero the object is deleted, while there's someone waiting to reference it. -> race
On a uniprocessor system this wouldn't be a problem, just a matter of disabling interrupts while in the kernel.
On a multiprocessor system this is a really big problem as you probably found out.

Does anyone know a way around this?

Cheers.
User avatar
Love4Boobies
Member
Member
Posts: 2111
Joined: Fri Mar 07, 2008 5:36 pm
Location: Bucharest, Romania

Re: Fixing potential race condition

Post by Love4Boobies »

You can use a lock, a semaphore or a monitor. There are also some other solutions around this but these are the best ways to go about it.
"Computers in the future may weigh no more than 1.5 tons.", Popular Mechanics (1949)
[ Project UDI ]
cyr1x
Member
Member
Posts: 207
Joined: Tue Aug 21, 2007 1:41 am
Location: Germany

Re: Fixing potential race condition

Post by cyr1x »

No this won't help because it could be preempted before it acquires the lock or on multiprocessor release can occur before reference. [-X
Anyway thanks. :)

Cheers.
User avatar
Love4Boobies
Member
Member
Posts: 2111
Joined: Fri Mar 07, 2008 5:36 pm
Location: Bucharest, Romania

Re: Fixing potential race condition

Post by Love4Boobies »

You can aquire the lock outside of Reference().
"Computers in the future may weigh no more than 1.5 tons.", Popular Mechanics (1949)
[ Project UDI ]
Laksen
Member
Member
Posts: 140
Joined: Fri Nov 09, 2007 3:30 am
Location: Aalborg, Denmark

Re: Fixing potential race condition

Post by Laksen »

Couldn't you do it using locked primitives like
InterlockedExchangeAdd(refCount, 1);

and

if(InterlockedExchangeAdd(refCount, -1) == 0)
delete this;
http://j-software.dk | JPasKernel - My Object Pascal kernel
User avatar
Brendan
Member
Member
Posts: 8561
Joined: Sat Jan 15, 2005 12:00 am
Location: At his keyboard!
Contact:

Re: Fixing potential race condition

Post by Brendan »

Hi,

First, let me point out that I've never used an OOP language and never used any sort of (software) garbage collection - AFAIK everything I'm about to say could be completely wrong...
cyr1x wrote:No this won't help because it could be preempted before it acquires the lock or on multiprocessor release can occur before reference.
It could be preempted before the "Reference()" function is even called.

However, how does the caller know that the object exists? Something must have told it the object exists. More importantly, something that has it's own reference must have told the caller that the object exists.

When an object is created the object creation code would increment the reference count and return a reference to the new object. Then, any time this reference is copied you'd increase the reference count *before* it's copied. For example, if threadA needs to tell threadB about the object, then it'd call the "Reference()" function and then give threadB a reference to the object.

Your problem seems to be that you're thinking about doing it the other way - e.g. give threadB a reference to the object and then call the "Reference()" function. AFAIK that will never work (unless you acquire a lock, then give threadB the reference, then let threadB call "Reference()" and then free the lock; but that's far too messy IMHO).

In this case, you don't need any locks. All you'd need is "lock inc [this->referenceCount]" in the "Reference()" function. In the "Release()" function you'd do "lock sub [this->referenceCount],1" followed by "je .delete" (or "jne .skipDelete").

The new problem is that all code must call "Reference()" before creating a copy of any reference; and if you can't trust programmers to call "free()" at the right time then you may not be able to trust them to call "Reference()" at the right time either... ;)


Cheers,

Brendan
For all things; perfection is, and will always remain, impossible to achieve in practice. However; by striving for perfection we create things that are as perfect as practically possible. Let the pursuit of perfection be our guide.
CodeCat
Member
Member
Posts: 158
Joined: Tue Sep 23, 2008 1:45 pm
Location: Eindhoven, Netherlands

Re: Fixing potential race condition

Post by CodeCat »

Brendan, he's using C++. He can just use the object destructor to decrease the reference count. ;)
User avatar
Walling
Member
Member
Posts: 158
Joined: Mon Dec 04, 2006 6:06 am
Location: Berlin, Germany

Re: Fixing potential race condition

Post by Walling »

I might be slightly off-topic. Just wanted to tell you that ref counting is only safe if you can guarantee that no cycles occur. If you're in a situation where object A and object B knows each other (two drivers relying on each other services?) then you have a cycle and that can be a problem. The objects will never be freed. The simplest situation where a cycle occur is when an object have a reference to itself. One solution is to let no cycles occur: Build a dependency graph and check it for cycles whenever an object is loaded. Another solution is to build a full fledged garbage collector, but I guess that is more difficult. Just wanted to tell you. You probably know this and have a solution for it. :)
User avatar
Combuster
Member
Member
Posts: 9301
Joined: Wed Oct 18, 2006 3:45 am
Libera.chat IRC: [com]buster
Location: On the balcony, where I can actually keep 1½m distance
Contact:

Re: Fixing potential race condition

Post by Combuster »

CodeCat wrote:Brendan, he's using C++. He can just use the object destructor to decrease the reference count. ;)
The idea of a destructor is that it destroys an object, while here we usually want to leave the object for other people to use.
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
CodeCat
Member
Member
Posts: 158
Joined: Tue Sep 23, 2008 1:45 pm
Location: Eindhoven, Netherlands

Re: Fixing potential race condition

Post by CodeCat »

True. I think most C++ programs get around that by having a separate 'reference' class that lowers the reference count when it's destructed. Kind of like a smart pointer but with reference counting facilities. I think the Boost library has one that might actually be usable for OSDev.
cyr1x
Member
Member
Posts: 207
Joined: Tue Aug 21, 2007 1:41 am
Location: Germany

Re: Fixing potential race condition

Post by cyr1x »

Hmm,
I think I have to clarify some points.
- The destructor does not decrease the reference count.
When the reference count drops to zero the destructor is called.
- There's no concept of thread's. Threads are object themselves.
In fact an object is bound to a context containing functions, variables, etc.
- The problem isn't the atomicity of the reference count itself! The problem is that the reference count may drop to zero, hence deleting the object, while there's someone who wants to acquire it.
-> When the context is preempted in the Reference() function before incrementing the count to an other context that decreases the count, probably deleting the object, then we have obviously have problems here as the object isn't valid anymore.
- Before Reference()ing an object, the kernel just checks if there's such an object, otherwise the request is just rejected.

Cheers.
ezeaguerre
Posts: 6
Joined: Mon Apr 30, 2007 3:21 pm

Re: Fixing potential race condition

Post by ezeaguerre »

Couldn't something like this work?

Code: Select all

void MyClass::Reference () {
	EntreCriticalSection ();
	if ( refCount <= 0 )
		reload ();
	refCount++;
	LeaveCriticalSection ();
}

void MyClass::Release () {
	EnterCriticalSection ();
	refCount--;
	if ( refCount == 0 )
		delete this;
	LeaveCriticalSection ();
}
or like this?

Code: Select all

EnterCriticalSection ();
if ( !myObject )
	myObject = new MyClass;
myObject->Reference ();
LeaveCriticalSection ();

void MyClass::Release () {
	EnterCriticalSection ();
	refCount--;
	if ( refCount == 0 )
		delete this;
	LeaveCriticalSection ();
}
or maybe I just don't get it O.o
User avatar
Brendan
Member
Member
Posts: 8561
Joined: Sat Jan 15, 2005 12:00 am
Location: At his keyboard!
Contact:

Re: Fixing potential race condition

Post by Brendan »

Hi,

Hmmm.

Here's an example of what I said last time. This is written in C because I don't know C++. AFAIK C++ uses almost identical concepts (except "MYOBJECT_DATA *myObjectData" becomes "this", and there's a few other differences with syntax/grammer).

Code: Select all

typedef struct {
	int referenceCount;
} MYOBJECT_DATA;


MYOBJECT_DATA *myObject_new(void) {
    MYOBJECT_DATA *myObjectData;

    myObjectData = malloc(sizeof(MYOBJECT_DATA));
    if(myObjectData != NULL) {
        myObjectData->referenceCount = 1;
        myObject_initialize(myObjectData);
    }
    return myObjectData;
}


void myObject_initialize(MYOBJECT_DATA *myObjectData) {
    /* ??? */
}

void myObject_destructor(MYOBJECT_DATA *myObjectData) {
    /* ??? */
}


void myObject_reference(MYOBJECT_DATA *myObjectData) {
    myObjectData->referenceCount++;      // Needs to be "lock inc dword [myObjectData->referenceCount]" for multi-CPU
}

void myObject_release(MYOBJECT_DATA *myObjectData) {
    myObjectData->referenceCount--;           // Needs to be "lock sub dword [myObjectData->referenceCount], 1" for multi-CPU
    if(myObjectData->referenceCount == 0) {   // Needs to be "jne .skip_the_next_2_lines" for multi-CPU
        myObject_destructor(myObjectData);
        free(myObjectData);
    }
}


void main(void) {
    MYOBJECT_DATA *myObjectData;

    myObjectData = myObject_new();

    myObject_reference(myObjectData);
    foo(myObjectData);

    myObject_reference(myObjectData);
    pthread_create(spareThread, myObjectData);

    myObject_release(myObjectData);
}


void foo(MYOBJECT_DATA *myObjectData) {
    / * ??? */
    myObject_release(myObjectData);
}


void spareThread(MYOBJECT_DATA *myObjectData) {
    if( rand() > RAND_MAX / 4) {
        myObject_reference(myObjectData);
        pthread_create(spareThread, myObjectData);
    }
    myObject_release(myObjectData);
}

Hopefully this makes sense...

There is no race condition (because the reference count is always increased *before* a reference is given to anything else).


Cheers,

Brendan
For all things; perfection is, and will always remain, impossible to achieve in practice. However; by striving for perfection we create things that are as perfect as practically possible. Let the pursuit of perfection be our guide.
cyr1x
Member
Member
Posts: 207
Joined: Tue Aug 21, 2007 1:41 am
Location: Germany

Re: Fixing potential race condition

Post by cyr1x »

Again,
the atomicity is not the problem!!
The problem is that an object can be deleted while there is somebody waiting to reference it.

Well I think I found a solution myself.

Code: Select all

bool Reference()
{
  lock;
  if(!ObjectIsAvailable(this))    // check if the object is available or it's deleted already
   return false;    
  refCount++;                  // <-- this was already atomic before!
  unlock;
  return true;
}

void Release()
{
  lock;
  refCount--;
  if(refCount == 0)           // check if the objects count is zero
  {
   removeFromObjectList(this); // remove from list ...
   delete this;                 // ... and delete it
  }
  unlock;
}

Why all this? I wanted the reference count to be 0. The point was not to trust the object creator that it removes the reference afterwards.
After thinking a while about Brendan's solution I think I change it to be 1 at initialisation.

@ezeaguerre: How to check if the reference count is zero as there isn't any object?
User avatar
Colonel Kernel
Member
Member
Posts: 1437
Joined: Tue Oct 17, 2006 6:06 pm
Location: Vancouver, BC, Canada
Contact:

Re: Fixing potential race condition

Post by Colonel Kernel »

Brendan wrote:

Code: Select all

void myObject_release(MYOBJECT_DATA *myObjectData) {
    myObjectData->referenceCount--;           // Needs to be "lock sub dword [myObjectData->referenceCount], 1" for multi-CPU
    if(myObjectData->referenceCount == 0) {   // Needs to be "jne .skip_the_next_2_lines" for multi-CPU
        myObject_destructor(myObjectData);
        free(myObjectData);
    }
}
As written, this is incorrect due to a race condition. Imagine this scenario:
  • The object has refcount 2.
  • Thread A calls release(), which decrements the refcount to 1.
  • Thread B calls release(), which decrements the refcount to 0.
  • Thread A checks the refcount, sees that it is 0, and destroys the object.
  • Thread B checks the refcount, sees that it is 0, and destroys the object again -> BANG!
The solution is to store the decremented value of the refcount in a local variable. Here it is with a bit of pseudo-code for the atomic instructions:

Code: Select all

void myObject_release(MYOBJECT_DATA *myObjectData) {
    int finalCount = atomic_decrement( &(myObjectData->referenceCount) );
    if (finalCount == 0) {
        myObject_destructor(myObjectData);
        free(myObjectData);
    }
}
cyr1x wrote:the atomicity is not the problem!!
The problem is that an object can be deleted while there is somebody waiting to reference it.
There is no "waiting to reference" an object. Either it is referenced, or it is not. If a thread holds a pointer to an object with refcount 0 (other than during the final execution of release()), it is the result of a double-deletion bug somewhere else in the code.

Brendan's implementation (with my fix) has been used successfully for decades in multi-threaded OO applications and frameworks (most notably in COM on Windows and Objective-C/NeXTStep/Cocoa on NeXT & Mac OS X). It definitely works, as long as objects start with a refcount of 1 and as long as clients of an object match calls to retain/release (a.k.a. AddRef(), Release(), etc.)
Top three reasons why my OS project died:
  1. Too much overtime at work
  2. Got married
  3. My brain got stuck in an infinite loop while trying to design the memory manager
Don't let this happen to you!
Post Reply