Last active
May 5, 2020 15:44
-
-
Save jonashaag/d455671003205120a864d3aa69536661 to your computer and use it in GitHub Desktop.
Pure Python solution to locking the GIL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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