codekingpro/portable-devtools
115k
1#ifndef Py_CPYTHON_LOCK_H2# error "this header file must not be included directly"3#endif4 5#define _Py_UNLOCKED 06#define _Py_LOCKED 17 8// A mutex that occupies one byte. The lock can be zero initialized to9// represent the unlocked state.10//11// Typical initialization:12// PyMutex m = (PyMutex){0};13//14// Or initialize as global variables:15// static PyMutex m;16//17// Typical usage:18// PyMutex_Lock(&m);19// ...20// PyMutex_Unlock(&m);21//22// The contents of the PyMutex are not part of the public API, but are23// described to aid in understanding the implementation and debugging. Only24// the two least significant bits are used. The remaining bits are always zero:25// 0b00: unlocked26// 0b01: locked27// 0b10: unlocked and has parked threads28// 0b11: locked and has parked threads29typedef struct PyMutex {30 uint8_t _bits; // (private)31} PyMutex;32 33// exported function for locking the mutex34PyAPI_FUNC(void) PyMutex_Lock(PyMutex *m);35 36// exported function for unlocking the mutex37PyAPI_FUNC(void) PyMutex_Unlock(PyMutex *m);38 39// exported function for checking if the mutex is locked40PyAPI_FUNC(int) PyMutex_IsLocked(PyMutex *m);41 42// Locks the mutex.43//44// If the mutex is currently locked, the calling thread will be parked until45// the mutex is unlocked. If the current thread holds the GIL, then the GIL46// will be released while the thread is parked.47static inline void48_PyMutex_Lock(PyMutex *m)49{50 uint8_t expected = _Py_UNLOCKED;51 if (!_Py_atomic_compare_exchange_uint8(&m->_bits, &expected, _Py_LOCKED)) {52 PyMutex_Lock(m);53 }54}55#define PyMutex_Lock _PyMutex_Lock56 57// Unlocks the mutex.58static inline void59_PyMutex_Unlock(PyMutex *m)60{61 uint8_t expected = _Py_LOCKED;62 if (!_Py_atomic_compare_exchange_uint8(&m->_bits, &expected, _Py_UNLOCKED)) {63 PyMutex_Unlock(m);64 }65}66#define PyMutex_Unlock _PyMutex_Unlock67 68// Checks if the mutex is currently locked.69static inline int70_PyMutex_IsLocked(PyMutex *m)71{72 return (_Py_atomic_load_uint8(&m->_bits) & _Py_LOCKED) != 0;73}74#define PyMutex_IsLocked _PyMutex_IsLocked75 