A couple garbage collector questions

Dan Sugalski dan at tuatha.sidhe.org
Wed Apr 4 16:39:07 EDT 2001


Douglas Alan <nessus at mit.edu> wrote:
> Andrew Kuchling <akuchlin at mems-exchange.org> writes:

>> Douglas Alan <nessus at mit.edu> writes:
>> > Why do you need to lock on increment/decrement?  Isn't incrementing or
>> > decrementing an integer an atomic operation on most CPU's?

>> Yes, but you don't know if your C compiler is smart enough to
>> generate such code for obj->refcnt++, so usually bits of assembler
>> are used.  For example, on Linux there are atomic_inc() and
>> atomic_dec() macros in asm/atomic.h.  I doubt there's a way of doing
>> this portably.

> Does the C compiler have to be smart for this to happen atomically?
> Generally wouldn't the normal stupid way be atomic?

No. On many processors it's a load, increment, store operation, and
very much not atomic. While it can be done atomically, that's usually
far more expensive. Better to do it the cheap way and have the
programmer do explicit locking (at this level at least) than force
the more expensive way all the time.

Also, depending on the code you might not get an atomic increment
anytway--if the compiler sees several refcount operations without
any code that injects uncertainty, it might coalesce them into a single
add or subtract, and those generally aren't atomic at all. You
may also have the processor getting involved, deferring writes
to the refcount location some and ultimately coalescing multiple
operations before it flushes the changed data out.

					Dan



More information about the Python-list mailing list