Skip to content

Instantly share code, notes, and snippets.

@jonashaag
Last active May 5, 2020 15:44
Show Gist options
  • Save jonashaag/d455671003205120a864d3aa69536661 to your computer and use it in GitHub Desktop.
Save jonashaag/d455671003205120a864d3aa69536661 to your computer and use it in GitHub Desktop.
Pure Python solution to locking the GIL
# Use libc in ctypes "PyDLL" mode, which prevents CPython from
# releasing the GIL during procedure calls.
_libc_name = ctypes.util.find_library("c")
if _libc_name is None:
raise RuntimeError("Cannot find libc")
libc_py = ctypes.PyDLL(_libc_name)
...
libc_py.usleep(...)
# --- Optional, for using with pickle ---
class PickleableCtypesFuncPtr:
"""A version of a ctypes._FuncPtr that can be pickled. The shared library
must be available in the depickling environment.
"""
def __init__(self, dll_type, lib, name):
self.__setstate__((dll_type, lib, name))
def __setstate__(self, state):
self.state = state
dll_type, lib, func = self.state
dll_loader = getattr(ctypes, dll_type)
self.funcptr = dll_loader(lib)[func]
def __getstate__(self):
return self.state
def __call__(self, *args):
return self.funcptr(*args)
usleep = PickleableCtypesFuncPtr("PyDLL", _libc_name, "usleep")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment