Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: Atomic ops as protection
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Atomic ops as protection



What if your atomic_compare_swap occurs immediately before the atomic_inc?
Thread 2 would be nuking the object while thread 1 is incrementing the refcount.
I might be missing something but I don't see what prevents this from occurring.



Ben Supnik wrote:
Hi Y'all,

I'm looking at using an atomic reference count as sort of protection for an object.

A thread using an object wants to be totally sure that a garbage collector isn't going to kill it off, so it bumps the reference count up while using it. Something like this...

struct obj {
  int  ref_count;
  ...
}

thread 1:

atomic_inc(&obj->ref_count);
do stuff to obj
atomic_dec(&obj->ref_count);

thread 2:

if(atomic_compare_swap(obj->ref_count, 0, -1))
   nuke the object

Do I have this right? If I was using a critical section I'd trust that the nuke-the-object code can't run at the same time as the do-stuff-to-obj code.

Is treating ref_count atomically enough to ensure that I won't get a nuke while processing the object?

I am assuming of course that no third thread randomly decrements the reference count without incrementing (which would "unlock" the object behind thread 1's back).

cheers
Ben




_______________________________________________
Do not post admin requests to the list. They will be ignored.
PerfOptimization-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


References: 
 >Atomic ops as protection (From: Ben Supnik <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.