Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-11-19 09:50:41

0001 #ifndef Py_CPYTHON_LOCK_H
0002 #  error "this header file must not be included directly"
0003 #endif
0004 
0005 #define _Py_UNLOCKED    0
0006 #define _Py_LOCKED      1
0007 
0008 // A mutex that occupies one byte. The lock can be zero initialized to
0009 // represent the unlocked state.
0010 //
0011 // Typical initialization:
0012 //   PyMutex m = (PyMutex){0};
0013 //
0014 // Or initialize as global variables:
0015 //   static PyMutex m;
0016 //
0017 // Typical usage:
0018 //   PyMutex_Lock(&m);
0019 //   ...
0020 //   PyMutex_Unlock(&m);
0021 //
0022 // The contents of the PyMutex are not part of the public API, but are
0023 // described to aid in understanding the implementation and debugging. Only
0024 // the two least significant bits are used. The remaining bits are always zero:
0025 // 0b00: unlocked
0026 // 0b01: locked
0027 // 0b10: unlocked and has parked threads
0028 // 0b11: locked and has parked threads
0029 typedef struct PyMutex {
0030     uint8_t _bits;  // (private)
0031 } PyMutex;
0032 
0033 // exported function for locking the mutex
0034 PyAPI_FUNC(void) PyMutex_Lock(PyMutex *m);
0035 
0036 // exported function for unlocking the mutex
0037 PyAPI_FUNC(void) PyMutex_Unlock(PyMutex *m);
0038 
0039 // Locks the mutex.
0040 //
0041 // If the mutex is currently locked, the calling thread will be parked until
0042 // the mutex is unlocked. If the current thread holds the GIL, then the GIL
0043 // will be released while the thread is parked.
0044 static inline void
0045 _PyMutex_Lock(PyMutex *m)
0046 {
0047     uint8_t expected = _Py_UNLOCKED;
0048     if (!_Py_atomic_compare_exchange_uint8(&m->_bits, &expected, _Py_LOCKED)) {
0049         PyMutex_Lock(m);
0050     }
0051 }
0052 #define PyMutex_Lock _PyMutex_Lock
0053 
0054 // Unlocks the mutex.
0055 static inline void
0056 _PyMutex_Unlock(PyMutex *m)
0057 {
0058     uint8_t expected = _Py_LOCKED;
0059     if (!_Py_atomic_compare_exchange_uint8(&m->_bits, &expected, _Py_UNLOCKED)) {
0060         PyMutex_Unlock(m);
0061     }
0062 }
0063 #define PyMutex_Unlock _PyMutex_Unlock