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.
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 »

the lock dec; jnz implementation fixes the condition under all circumstances (since the flags get set according to the written result) and works on 386s

for atomic decrement in your style, you'd need to adapt fetch-and-add (xadd), but it requires a 486 and costs more time.
"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 ]
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 »

Combuster wrote:the lock dec; jnz implementation fixes the condition under all circumstances (since the flags get set according to the written result) and works on 386s

for atomic decrement in your style, you'd need to adapt fetch-and-add (xadd), but it requires a 486 and costs more time.
This is what I get for reading the C pseudo-code and ignoring the assembler. :roll:
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!
cyr1x
Member
Member
Posts: 207
Joined: Tue Aug 21, 2007 1:41 am
Location: Germany

Re: Fixing potential race condition

Post by cyr1x »

Thanks to you all. :D
Now I have something to play for the moment, 'redesigning' included.

Cheers.
thre3dee
Member
Member
Posts: 34
Joined: Mon Nov 03, 2008 7:42 pm

Re: Fixing potential race condition

Post by thre3dee »

As mentioned before, the owner should pass a new reference to the customer (and have a lock in the retain/release functions) before releasing its instance. This would satisfy all conditions as the customer would be guaranteed its own reference by the time the owner reaches the release(). Any other threads retaining and releasing references would have no impact as they have their own reference to act on via the above method.

Code: Select all

void *retain_object(void *obj)
{
	struct object_base *o = (struct object_base *)obj;
	lock o->refs;
	o->refs++;
	unlock;
	return obj;
}

struct my_object *o = my_object_new();
// regardless of thread
other = retain_object(o);
release_object(o);
Post Reply