cpython/Include/internal/pycore_semaphore.h
Victor Stinner 74e425ec18
gh-110014: Fix _POSIX_THREADS and _POSIX_SEMAPHORES usage (#110139)
* pycore_pythread.h is now the central place to make sure that
  _POSIX_THREADS and _POSIX_SEMAPHORES macros are defined if
  available.
* Make sure that pycore_pythread.h is included when _POSIX_THREADS
  and _POSIX_SEMAPHORES macros are tested.
* PY_TIMEOUT_MAX is now defined as a constant, since its value
  depends on _POSIX_THREADS, instead of being defined as a macro.
* Prevent integer overflow in the preprocessor when computing
  PY_TIMEOUT_MAX_VALUE on Windows:
  replace "0xFFFFFFFELL * 1000 < LLONG_MAX"
  with "0xFFFFFFFELL < LLONG_MAX / 1000".
* Document the change and give hints how to fix affected code.
* Add an exception for PY_TIMEOUT_MAX  name to smelly.py
* Add PY_TIMEOUT_MAX to the stable ABI
2023-09-30 19:25:54 +02:00

66 lines
1.7 KiB
C

// The _PySemaphore API a simplified cross-platform semaphore used to implement
// wakeup/sleep.
#ifndef Py_INTERNAL_SEMAPHORE_H
#define Py_INTERNAL_SEMAPHORE_H
#ifndef Py_BUILD_CORE
# error "this header requires Py_BUILD_CORE define"
#endif
#include "pycore_pythread.h" // _POSIX_SEMAPHORES
#include "pycore_time.h" // _PyTime_t
#ifdef MS_WINDOWS
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#elif defined(HAVE_PTHREAD_H)
# include <pthread.h>
#elif defined(HAVE_PTHREAD_STUBS)
# include "cpython/pthread_stubs.h"
#else
# error "Require native threads. See https://bugs.python.org/issue31370"
#endif
#if (defined(_POSIX_SEMAPHORES) && (_POSIX_SEMAPHORES+0) != -1 && \
defined(HAVE_SEM_TIMEDWAIT))
# define _Py_USE_SEMAPHORES
# include <semaphore.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _PySemaphore {
#if defined(MS_WINDOWS)
HANDLE platform_sem;
#elif defined(_Py_USE_SEMAPHORES)
sem_t platform_sem;
#else
pthread_mutex_t mutex;
pthread_cond_t cond;
int counter;
#endif
} _PySemaphore;
// Puts the current thread to sleep until _PySemaphore_Wakeup() is called.
// If `detach` is true, then the thread will detach/release the GIL while
// sleeping.
PyAPI_FUNC(int)
_PySemaphore_Wait(_PySemaphore *sema, _PyTime_t timeout_ns, int detach);
// Wakes up a single thread waiting on sema. Note that _PySemaphore_Wakeup()
// can be called before _PySemaphore_Wait().
PyAPI_FUNC(void)
_PySemaphore_Wakeup(_PySemaphore *sema);
// Initializes/destroys a semaphore
PyAPI_FUNC(void) _PySemaphore_Init(_PySemaphore *sema);
PyAPI_FUNC(void) _PySemaphore_Destroy(_PySemaphore *sema);
#ifdef __cplusplus
}
#endif
#endif /* !Py_INTERNAL_SEMAPHORE_H */