[pypy-dev] Implementing CAS

Timothy Baldridge tbaldridge at gmail.com
Tue Mar 22 21:41:19 CET 2011

After my last discussion about getting some multi-threading
primitives, I took a look at how locks are implemented in PyPy. PyPy
currently uses OS level mutexes...which is okay for most uses, but in
my case, I need super fast spinlocks, and for that I need a CAS
operation. What I'm looking for is a bit of direction on how to go
about implementing this function (shown in C syntax):

int cas(*expected, *new, **location)

This function looks at the contents of the data pointed at by
**location. If the contents == *expected, the contents are replaced
with *new and the function returns true. Otherwise the function
returns false.

There are several issues I see with implementing this in python:

1) **location must be pointer to a object pointer, is this even
possible in PyPy?
2) I'd rather not call an FFI C function for this, when this entire
function could be inlined with just a few lines of assembly (CAS is a
single instruction on x86). So could this be created as a C function
that is simply inserted into the generated C code, so that GCC could
inline it at will?

I'm just brainstorming here. No matter how you dice it, CAS is pretty
much a prerequisite to any sort of multi-threaded programming these
days. That is unless you want to spend thousands of clock cycles in
context switches.


“One of the main causes of the fall of the Roman Empire was
that–lacking zero–they had no way to indicate successful termination
of their C programs.”
(Robert Firth)

More information about the Pypy-dev mailing list