| 1 |
// The _PySemaphore API a simplified cross-platform semaphore used to implement |
| 2 |
// wakeup/sleep. |
| 3 |
#ifndef Py_INTERNAL_SEMAPHORE_H |
| 4 |
#define Py_INTERNAL_SEMAPHORE_H |
| 5 |
|
| 6 |
#ifndef Py_BUILD_CORE |
| 7 |
# error "this header requires Py_BUILD_CORE define" |
| 8 |
#endif |
| 9 |
|
| 10 |
#include "pycore_pythread.h" // _POSIX_SEMAPHORES |
| 11 |
|
| 12 |
#ifdef MS_WINDOWS |
| 13 |
# ifndef WIN32_LEAN_AND_MEAN |
| 14 |
# define WIN32_LEAN_AND_MEAN |
| 15 |
# endif |
| 16 |
# include <windows.h> |
| 17 |
#elif defined(HAVE_PTHREAD_H) |
| 18 |
# include <pthread.h> |
| 19 |
#elif defined(HAVE_PTHREAD_STUBS) |
| 20 |
# include "cpython/pthread_stubs.h" |
| 21 |
#else |
| 22 |
# error "Require native threads. See https://bugs.python.org/issue31370" |
| 23 |
#endif |
| 24 |
|
| 25 |
#if (defined(_POSIX_SEMAPHORES) && (_POSIX_SEMAPHORES+0) != -1 && \ |
| 26 |
defined(HAVE_SEM_TIMEDWAIT)) |
| 27 |
# define _Py_USE_SEMAPHORES |
| 28 |
# include <semaphore.h> |
| 29 |
#endif |
| 30 |
|
| 31 |
|
| 32 |
#ifdef __cplusplus |
| 33 |
extern "C" { |
| 34 |
#endif |
| 35 |
|
| 36 |
typedef struct _PySemaphore { |
| 37 |
#if defined(MS_WINDOWS) |
| 38 |
HANDLE platform_sem; |
| 39 |
#elif defined(_Py_USE_SEMAPHORES) |
| 40 |
sem_t platform_sem; |
| 41 |
#else |
| 42 |
pthread_mutex_t mutex; |
| 43 |
pthread_cond_t cond; |
| 44 |
int counter; |
| 45 |
#endif |
| 46 |
} _PySemaphore; |
| 47 |
|
| 48 |
// Puts the current thread to sleep until _PySemaphore_Wakeup() is called. |
| 49 |
// If `detach` is true, then the thread will detach/release the GIL while |
| 50 |
// sleeping. |
| 51 |
PyAPI_FUNC(int) |
| 52 |
_PySemaphore_Wait(_PySemaphore *sema, PyTime_t timeout_ns, int detach); |
| 53 |
|
| 54 |
// Wakes up a single thread waiting on sema. Note that _PySemaphore_Wakeup() |
| 55 |
// can be called before _PySemaphore_Wait(). |
| 56 |
PyAPI_FUNC(void) |
| 57 |
_PySemaphore_Wakeup(_PySemaphore *sema); |
| 58 |
|
| 59 |
// Initializes/destroys a semaphore |
| 60 |
PyAPI_FUNC(void) _PySemaphore_Init(_PySemaphore *sema); |
| 61 |
PyAPI_FUNC(void) _PySemaphore_Destroy(_PySemaphore *sema); |
| 62 |
|
| 63 |
|
| 64 |
#ifdef __cplusplus |
| 65 |
} |
| 66 |
#endif |
| 67 |
#endif /* !Py_INTERNAL_SEMAPHORE_H */ |