Lockless algorithms in python (Nothing to do with GIL)

sturlamolden sturlamolden at yahoo.no
Mon Jun 28 23:32:27 EDT 2010


On 29 Jun, 05:11, Ryan Kelly <r... at rfk.id.au> wrote:

> Very interesting idea.  Will it work if accessed through ctypes?
>
>    ticker = ctypes.c_int.in_dll(ctypes.pythonapi,"_Py_Ticker")
>    ticker.value = 0x7fffffff
>
> Or does ctypes muck with the GIL in a way that would break this idea?
>

>>> ctypes.pythonapi
<PyDLL 'python dll', handle 1e000000 at 1ffead0>

It's a PyDLL, so it should not mock with the GIL.


from contextlib import contextmanager
import ctypes
_Py_Ticker = ctypes.c_int.in_dll(ctypes.pythonapi,"_Py_Ticker")

@contextmanager
def atomic():
    tmp = _Py_Ticker.value
    _Py_Ticker.value = 0x7fffffff
    yield
    _Py_Ticker.value = tmp - 1


Now we can do

with atomic():
    # whatever
    pass

Just make sure we don't call extension code that releases the GIL :)








More information about the Python-list mailing list