| 1 |
#include "pythoncapi_compat.h" |
| 2 |
|
| 3 |
#define PY_SSIZE_T_CLEAN |
| 4 |
#include <Python.h> |
| 5 |
#include "librt_threading.h" |
| 6 |
#include "mypyc_util.h" |
| 7 |
|
| 8 |
#if !defined(_WIN32) |
| 9 |
#include <unistd.h> |
| 10 |
#include <errno.h> |
| 11 |
#endif |
| 12 |
|
| 13 |
#if CPY_3_14_FEATURES |
| 14 |
|
| 15 |
// Python 3.14+ (all platforms, with or without the GIL): Use PyMutex (1-byte |
| 16 |
// atomic lock with parking lot). PyMutex gives better interruptibility than the |
| 17 |
// pthread fallback, and its fast release path is competitive with sem_t. |
| 18 |
// PyMutex_LockFast, _PyMutex_LockTimed, and _PY_LOCK_DETACH are internal |
| 19 |
// CPython APIs that might change across minor releases. |
| 20 |
#define LOCK_BACKEND_PYMUTEX |
| 21 |
#ifndef Py_BUILD_CORE |
| 22 |
#define Py_BUILD_CORE |
| 23 |
#endif |
| 24 |
#include "internal/pycore_lock.h" |
| 25 |
|
| 26 |
#elif defined(_WIN32) |
| 27 |
|
| 28 |
// Python <3.14 on Windows: Use Slim Reader/Writer Lock |
| 29 |
#define LOCK_BACKEND_SRWLOCK |
| 30 |
#include <windows.h> |
| 31 |
|
| 32 |
#else |
| 33 |
|
| 34 |
// Python <3.14 on POSIX. |
| 35 |
// |
| 36 |
// Prefer a POSIX unnamed semaphore when the platform supports it well and the |
| 37 |
// GIL is enabled, and fall back to a pthread mutex + condition variable |
| 38 |
// otherwise. We use the same test CPython uses to pick its semaphore-based lock |
| 39 |
// (see Python/thread_pthread.h): an unnamed semaphore is only usable when |
| 40 |
// sem_init() actually works AND a timed wait is available. Notably this is true |
| 41 |
// on Linux but false on macOS (whose sem_init() is a non-functional stub), so |
| 42 |
// macOS uses the mutex+condvar fallback. Free-threaded builds also use the |
| 43 |
// mutex+condvar fallback because the semaphore backend's `locked` bookkeeping |
| 44 |
// relies on GIL serialization. |
| 45 |
#if !defined(Py_GIL_DISABLED) && \ |
| 46 |
defined(_POSIX_SEMAPHORES) && (_POSIX_SEMAPHORES + 0) != -1 && \ |
| 47 |
(defined(HAVE_SEM_TIMEDWAIT) || defined(HAVE_SEM_CLOCKWAIT)) |
| 48 |
#define LOCK_BACKEND_SEM |
| 49 |
#include <semaphore.h> |
| 50 |
#else |
| 51 |
#define LOCK_BACKEND_PTHREAD |
| 52 |
#include <pthread.h> |
| 53 |
#endif |
| 54 |
|
| 55 |
#endif |
| 56 |
|
| 57 |
// |
| 58 |
// Lock |
| 59 |
// |
| 60 |
// A fast mutex lock for use from mypyc-compiled code. |
| 61 |
// |
| 62 |
// On Python 3.14+ (all platforms), this uses CPython's PyMutex, a 1-byte atomic |
| 63 |
// lock backed by a parking lot for contended waits. PyMutex automatically |
| 64 |
// releases the GIL when blocking. |
| 65 |
// |
| 66 |
// On Python 3.13 and earlier with Windows, this uses an SRWLOCK (Slim |
| 67 |
// Reader/Writer Lock) plus a CONDITION_VARIABLE guarding a `locked` flag. The SRWLOCK only |
| 68 |
// protects the flag and is never held across the user's critical section, so |
| 69 |
// release() may be called from a thread other than the acquirer (matching |
| 70 |
// threading.Lock semantics). This mirrors CPython's Windows lock (NRMUTEX in |
| 71 |
// Python/thread_nt.h) and is the Windows twin of the POSIX pthread+condvar |
| 72 |
// backend below. |
| 73 |
// |
| 74 |
// On Python 3.13 and earlier with POSIX systems, there are two backends, both |
| 75 |
// of which allow release() from a thread other than the one that acquired the |
| 76 |
// lock (matching threading.Lock semantics): |
| 77 |
// |
| 78 |
// - Where unnamed POSIX semaphores work well (e.g. Linux) and the GIL is |
| 79 |
// enabled, this uses a sem_t initialized to 1: acquire is sem_wait, release |
| 80 |
// is sem_post. Semaphores have no ownership concept, so cross-thread release |
| 81 |
// is directly well-defined. |
| 82 |
// |
| 83 |
// - Otherwise (e.g. macOS, whose sem_init() is a non-functional stub, and |
| 84 |
// free-threaded builds), this uses a pthread mutex + condition variable |
| 85 |
// guarding a `locked` flag. The mutex only protects the flag and is never |
| 86 |
// held across the user's critical section, so the OS mutex is always |
| 87 |
// unlocked on the same thread that locked it. |
| 88 |
// |
| 89 |
|
| 90 |
// ---------- Platform-specific lock state ---------- |
| 91 |
|
| 92 |
#if defined(LOCK_BACKEND_PYMUTEX) |
| 93 |
|
| 94 |
typedef struct { |
| 95 |
PyObject_HEAD |
| 96 |
PyMutex mutex; |
| 97 |
} LockObject; |
| 98 |
|
| 99 |
#elif defined(LOCK_BACKEND_SRWLOCK) |
| 100 |
|
| 101 |
typedef struct { |
| 102 |
PyObject_HEAD |
| 103 |
// The SRWLOCK below does NOT represent the Python lock; like the pthread |
| 104 |
// fallback's `mut`, it only guards `locked` and the condition variable, |
| 105 |
// and is held just long enough to inspect/flip the flag -- never across |
| 106 |
// the user's critical section. That is what allows release() from a |
| 107 |
// thread other than the acquirer: SRWLOCK's same-thread-release rule is |
| 108 |
// never violated, and clearing `locked` is just a guarded store. This |
| 109 |
// mirrors CPython's Windows lock (NRMUTEX in Python/thread_nt.h). |
| 110 |
SRWLOCK srw; |
| 111 |
CONDITION_VARIABLE lock_released; |
| 112 |
int locked; // 0=unlocked, 1=locked; protected by `srw` |
| 113 |
} LockObject; |
| 114 |
|
| 115 |
#elif defined(LOCK_BACKEND_SEM) |
| 116 |
|
| 117 |
typedef struct { |
| 118 |
PyObject_HEAD |
| 119 |
sem_t sem; // counting semaphore, initialized to 1 |
| 120 |
// Tracks the locked state for locked() and release-unlocked detection. |
| 121 |
// The semaphore itself is the source of truth for mutual exclusion; this |
| 122 |
// flag is advisory bookkeeping. It is set after a successful acquire and |
| 123 |
// cleared before sem_post in release. |
| 124 |
// |
| 125 |
// This backend is only selected when the GIL is enabled, so this flag is a |
| 126 |
// plain int relying on the GIL for serialization: it is only ever touched |
| 127 |
// with the GIL held (the blocking sem_wait drops the GIL, but the flag |
| 128 |
// store happens after the GIL is reacquired). This mirrors the old |
| 129 |
// PyThread_type_lock wrapper bookkeeping used by CPython 3.12 and earlier, |
| 130 |
// where _thread lock kept a plain `char locked` for sanity checks and |
| 131 |
// locked(). |
| 132 |
int locked; |
| 133 |
} LockObject; |
| 134 |
|
| 135 |
#else // pthread mutex + condvar fallback |
| 136 |
|
| 137 |
typedef struct { |
| 138 |
PyObject_HEAD |
| 139 |
// The pthread mutex below does NOT represent the Python lock; it only |
| 140 |
// guards the `locked` flag and the condition variable. The Python lock |
| 141 |
// state is `locked` itself. This indirection (matching CPython's POSIX |
| 142 |
// lock) is what allows release() from a thread other than the acquirer: |
| 143 |
// `mut` is always locked and unlocked within a single call on a single |
| 144 |
// thread, so pthread's same-thread-unlock rule is never violated. |
| 145 |
pthread_mutex_t mut; |
| 146 |
pthread_cond_t lock_released; |
| 147 |
// Always accessed while holding `mut` (including the locked() reader), |
| 148 |
// so a plain int is sufficient -- the mutex provides the ordering. |
| 149 |
// Matches CPython's pthread_lock.locked (a plain char). |
| 150 |
int locked; // 0=unlocked, 1=locked; protected by `mut` |
| 151 |
} LockObject; |
| 152 |
|
| 153 |
#endif |
| 154 |
|
| 155 |
// ---------- Platform-specific init/acquire/release ---------- |
| 156 |
|
| 157 |
static inline int |
| 158 |
Lock_init_internal(LockObject *self) |
| 159 |
{ |
| 160 |
#if defined(LOCK_BACKEND_PYMUTEX) |
| 161 |
self->mutex = (PyMutex){0}; |
| 162 |
#elif defined(LOCK_BACKEND_SRWLOCK) |
| 163 |
InitializeSRWLock(&self->srw); |
| 164 |
InitializeConditionVariable(&self->lock_released); |
| 165 |
self->locked = 0; |
| 166 |
#elif defined(LOCK_BACKEND_SEM) |
| 167 |
if (sem_init(&self->sem, 0, 1) != 0) { |
| 168 |
PyErr_SetFromErrno(PyExc_OSError); |
| 169 |
return -1; |
| 170 |
} |
| 171 |
self->locked = 0; |
| 172 |
#else |
| 173 |
int status = pthread_mutex_init(&self->mut, NULL); |
| 174 |
if (status != 0) { |
| 175 |
errno = status; |
| 176 |
PyErr_SetFromErrno(PyExc_OSError); |
| 177 |
return -1; |
| 178 |
} |
| 179 |
|
| 180 |
status = pthread_cond_init(&self->lock_released, NULL); |
| 181 |
if (status != 0) { |
| 182 |
pthread_mutex_destroy(&self->mut); |
| 183 |
errno = status; |
| 184 |
PyErr_SetFromErrno(PyExc_OSError); |
| 185 |
return -1; |
| 186 |
} |
| 187 |
|
| 188 |
self->locked = 0; |
| 189 |
#endif |
| 190 |
return 0; |
| 191 |
} |
| 192 |
|
| 193 |
// Try to acquire the lock. Returns 1 (true) on success, 0 (false) if |
| 194 |
// non-blocking and the lock is held, or -1 if interrupted by an error-raising |
| 195 |
// signal handler. |
| 196 |
static int |
| 197 |
Lock_acquire_impl(LockObject *self, int blocking) |
| 198 |
{ |
| 199 |
#if defined(LOCK_BACKEND_PYMUTEX) |
| 200 |
if (!blocking) { |
| 201 |
PyLockStatus r = _PyMutex_LockTimed(&self->mutex, 0, _Py_LOCK_DONT_DETACH); |
| 202 |
return r == PY_LOCK_ACQUIRED; |
| 203 |
} |
| 204 |
if (PyMutex_LockFast(&self->mutex)) { |
| 205 |
return 1; |
| 206 |
} |
| 207 |
PyLockStatus r = _PyMutex_LockTimed(&self->mutex, -1, |
| 208 |
_PY_LOCK_DETACH | _PY_LOCK_HANDLE_SIGNALS); |
| 209 |
if (r == PY_LOCK_INTR) { |
| 210 |
return -1; |
| 211 |
} |
| 212 |
return 1; |
| 213 |
|
| 214 |
#elif defined(LOCK_BACKEND_SRWLOCK) |
| 215 |
// `srw` only guards `locked` and the condition variable; it is held just |
| 216 |
// long enough to inspect/flip the flag, never across the user's critical |
| 217 |
// section. This is what lets a different thread call release(). |
| 218 |
// |
| 219 |
// Fast path: grab the lock without releasing the GIL if it is free. This is |
| 220 |
// also the whole story in the non-blocking case. |
| 221 |
AcquireSRWLockExclusive(&self->srw); |
| 222 |
if (!self->locked) { |
| 223 |
self->locked = 1; |
| 224 |
ReleaseSRWLockExclusive(&self->srw); |
| 225 |
return 1; |
| 226 |
} |
| 227 |
ReleaseSRWLockExclusive(&self->srw); |
| 228 |
if (!blocking) { |
| 229 |
return 0; |
| 230 |
} |
| 231 |
|
| 232 |
// Slow path: wait for the lock to be released, with the GIL dropped so |
| 233 |
// other Python threads can run (and release the lock). |
| 234 |
// SleepConditionVariableSRW atomically releases the SRWLOCK while sleeping |
| 235 |
// and reacquires it on wake, exactly like pthread_cond_wait. |
| 236 |
Py_BEGIN_ALLOW_THREADS |
| 237 |
AcquireSRWLockExclusive(&self->srw); |
| 238 |
while (self->locked) { |
| 239 |
SleepConditionVariableSRW(&self->lock_released, &self->srw, INFINITE, 0); |
| 240 |
} |
| 241 |
self->locked = 1; |
| 242 |
ReleaseSRWLockExclusive(&self->srw); |
| 243 |
Py_END_ALLOW_THREADS |
| 244 |
return 1; |
| 245 |
|
| 246 |
#elif defined(LOCK_BACKEND_SEM) |
| 247 |
// A semaphore has no ownership: any thread may sem_post a token that |
| 248 |
// another thread consumed via sem_wait, so cross-thread release is |
| 249 |
// directly well-defined. `locked` is advisory bookkeeping for locked() |
| 250 |
// and for guarding against releasing an unheld lock. |
| 251 |
// |
| 252 |
// Fast path: try a non-blocking acquire first to avoid GIL release/reacquire |
| 253 |
// overhead in the common uncontended case. This is also the whole story in |
| 254 |
// the non-blocking case. |
| 255 |
{ |
| 256 |
int status; |
| 257 |
do { |
| 258 |
status = sem_trywait(&self->sem); |
| 259 |
} while (status == -1 && errno == EINTR); |
| 260 |
if (status == 0) { |
| 261 |
self->locked = 1; |
| 262 |
return 1; |
| 263 |
} |
| 264 |
} |
| 265 |
if (!blocking) { |
| 266 |
return 0; // EAGAIN: already held |
| 267 |
} |
| 268 |
|
| 269 |
// Slow path: block with the GIL dropped so other Python threads can run |
| 270 |
// (and release the lock). If a signal interrupts sem_wait(), run pending |
| 271 |
// Python signal handlers with the GIL held; retry unless a handler raises. |
| 272 |
for (;;) { |
| 273 |
int status; |
| 274 |
int err = 0; |
| 275 |
|
| 276 |
Py_BEGIN_ALLOW_THREADS |
| 277 |
status = sem_wait(&self->sem); |
| 278 |
if (status == -1) { |
| 279 |
err = errno; |
| 280 |
} |
| 281 |
Py_END_ALLOW_THREADS |
| 282 |
|
| 283 |
if (status == 0) { |
| 284 |
self->locked = 1; |
| 285 |
return 1; |
| 286 |
} |
| 287 |
|
| 288 |
if (err != EINTR) { |
| 289 |
PyErr_SetFromErrno(PyExc_OSError); |
| 290 |
return -1; |
| 291 |
} |
| 292 |
|
| 293 |
if (Py_MakePendingCalls() < 0) { |
| 294 |
return -1; |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
#else // pthread mutex + condvar fallback |
| 299 |
// `mut` only guards `locked` and the condition variable; it is held just |
| 300 |
// long enough to inspect/flip the flag, never across the user's critical |
| 301 |
// section. This is what lets a different thread call release(). |
| 302 |
// |
| 303 |
// Fast path: grab the lock without releasing the GIL if it is free. This is |
| 304 |
// also the whole story in the non-blocking case. |
| 305 |
pthread_mutex_lock(&self->mut); |
| 306 |
if (!self->locked) { |
| 307 |
self->locked = 1; |
| 308 |
pthread_mutex_unlock(&self->mut); |
| 309 |
return 1; |
| 310 |
} |
| 311 |
pthread_mutex_unlock(&self->mut); |
| 312 |
if (!blocking) { |
| 313 |
return 0; |
| 314 |
} |
| 315 |
|
| 316 |
// Slow path: wait for the lock to be released, with the GIL dropped so |
| 317 |
// other Python threads can run (and release the lock). If we wake but do |
| 318 |
// not get the lock, give pending Python signal handlers a chance to run, |
| 319 |
// matching CPython's pthread fallback. |
| 320 |
for (;;) { |
| 321 |
int acquired = 0; |
| 322 |
int interrupted = 0; |
| 323 |
int status; |
| 324 |
|
| 325 |
Py_BEGIN_ALLOW_THREADS |
| 326 |
status = pthread_mutex_lock(&self->mut); |
| 327 |
if (status == 0) { |
| 328 |
while (self->locked) { |
| 329 |
status = pthread_cond_wait(&self->lock_released, &self->mut); |
| 330 |
if (status != 0) { |
| 331 |
break; |
| 332 |
} |
| 333 |
if (self->locked) { |
| 334 |
interrupted = 1; |
| 335 |
break; |
| 336 |
} |
| 337 |
} |
| 338 |
if (status == 0 && !interrupted) { |
| 339 |
self->locked = 1; |
| 340 |
acquired = 1; |
| 341 |
} |
| 342 |
int unlock_status = pthread_mutex_unlock(&self->mut); |
| 343 |
if (status == 0) { |
| 344 |
status = unlock_status; |
| 345 |
} |
| 346 |
} |
| 347 |
Py_END_ALLOW_THREADS |
| 348 |
|
| 349 |
if (status != 0) { |
| 350 |
errno = status; |
| 351 |
PyErr_SetFromErrno(PyExc_OSError); |
| 352 |
return -1; |
| 353 |
} |
| 354 |
if (acquired) { |
| 355 |
return 1; |
| 356 |
} |
| 357 |
if (interrupted && Py_MakePendingCalls() < 0) { |
| 358 |
return -1; |
| 359 |
} |
| 360 |
} |
| 361 |
#endif |
| 362 |
} |
| 363 |
|
| 364 |
// Release the lock. Returns 0 on success, -1 if the lock was not held. |
| 365 |
static int |
| 366 |
Lock_release_impl(LockObject *self) |
| 367 |
{ |
| 368 |
#if defined(LOCK_BACKEND_PYMUTEX) |
| 369 |
// threading.Lock is unowned, so release() may be called from a different |
| 370 |
// thread than acquire(). CPython's atomic _PyMutex_TryUnlock() is not part |
| 371 |
// of the public API and is not exported by all CPython builds. This fast |
| 372 |
// partial-replacement path deliberately avoids a second guard mutex: |
| 373 |
// ordinary release() of an unlocked lock raises RuntimeError, but racy |
| 374 |
// erroneous release() calls are undefined behavior and may make |
| 375 |
// PyMutex_Unlock() abort. |
| 376 |
if (!PyMutex_IsLocked(&self->mutex)) { |
| 377 |
return -1; |
| 378 |
} |
| 379 |
PyMutex_Unlock(&self->mutex); |
| 380 |
return 0; |
| 381 |
|
| 382 |
#elif defined(LOCK_BACKEND_SRWLOCK) |
| 383 |
AcquireSRWLockExclusive(&self->srw); |
| 384 |
if (!self->locked) { |
| 385 |
ReleaseSRWLockExclusive(&self->srw); |
| 386 |
return -1; |
| 387 |
} |
| 388 |
self->locked = 0; |
| 389 |
// Wake one waiter (if any). Signalling under `srw` is fine and avoids a |
| 390 |
// lost-wakeup race. |
| 391 |
WakeConditionVariable(&self->lock_released); |
| 392 |
ReleaseSRWLockExclusive(&self->srw); |
| 393 |
return 0; |
| 394 |
|
| 395 |
#elif defined(LOCK_BACKEND_SEM) |
| 396 |
// Check-then-clear the flag, then post. This backend is only selected when |
| 397 |
// the GIL is enabled, so the check and clear are serialized without an |
| 398 |
// atomic. |
| 399 |
if (!self->locked) { |
| 400 |
return -1; |
| 401 |
} |
| 402 |
self->locked = 0; |
| 403 |
sem_post(&self->sem); |
| 404 |
return 0; |
| 405 |
|
| 406 |
#else // pthread mutex + condvar fallback |
| 407 |
pthread_mutex_lock(&self->mut); |
| 408 |
if (!self->locked) { |
| 409 |
pthread_mutex_unlock(&self->mut); |
| 410 |
return -1; |
| 411 |
} |
| 412 |
self->locked = 0; |
| 413 |
// Wake one waiter (if any). Signalling under `mut` is fine and avoids a |
| 414 |
// lost-wakeup race. |
| 415 |
pthread_cond_signal(&self->lock_released); |
| 416 |
pthread_mutex_unlock(&self->mut); |
| 417 |
return 0; |
| 418 |
#endif |
| 419 |
} |
| 420 |
|
| 421 |
static inline int |
| 422 |
Lock_is_locked(LockObject *self) |
| 423 |
{ |
| 424 |
#if defined(LOCK_BACKEND_PYMUTEX) |
| 425 |
return PyMutex_IsLocked(&self->mutex); |
| 426 |
#elif defined(LOCK_BACKEND_SRWLOCK) |
| 427 |
// locked() is not expected to be on a perf-critical path, so take the |
| 428 |
// SRWLOCK (shared) for a clean read of the guarded flag rather than |
| 429 |
// relying on an atomic/volatile field. |
| 430 |
AcquireSRWLockShared(&self->srw); |
| 431 |
int result = self->locked; |
| 432 |
ReleaseSRWLockShared(&self->srw); |
| 433 |
return result; |
| 434 |
#elif defined(LOCK_BACKEND_SEM) |
| 435 |
// The flag is GIL-serialized (see the struct comment); locked() is a |
| 436 |
// plain read, matching the old CPython _thread lock bookkeeping described |
| 437 |
// above. |
| 438 |
return self->locked != 0; |
| 439 |
#else // pthread mutex + condvar fallback |
| 440 |
// `locked` is only ever accessed under `mut`; take it for a clean read. |
| 441 |
// locked() is not expected to be on a perf-critical path. |
| 442 |
pthread_mutex_lock(&self->mut); |
| 443 |
int result = self->locked; |
| 444 |
pthread_mutex_unlock(&self->mut); |
| 445 |
return result; |
| 446 |
#endif |
| 447 |
} |
| 448 |
|
| 449 |
// ---------- Python type methods (shared across platforms) ---------- |
| 450 |
|
| 451 |
static PyTypeObject LockType; |
| 452 |
|
| 453 |
static PyObject * |
| 454 |
Lock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
| 455 |
{ |
| 456 |
if (type != &LockType) { |
| 457 |
PyErr_SetString(PyExc_TypeError, "Lock cannot be subclassed"); |
| 458 |
return NULL; |
| 459 |
} |
| 460 |
|
| 461 |
LockObject *self = (LockObject *)type->tp_alloc(type, 0); |
| 462 |
if (self != NULL && Lock_init_internal(self) < 0) { |
| 463 |
type->tp_free((PyObject *)self); |
| 464 |
return NULL; |
| 465 |
} |
| 466 |
return (PyObject *)self; |
| 467 |
} |
| 468 |
|
| 469 |
static int |
| 470 |
Lock_init(LockObject *self, PyObject *args, PyObject *kwds) |
| 471 |
{ |
| 472 |
if (!PyArg_ParseTuple(args, "")) { |
| 473 |
return -1; |
| 474 |
} |
| 475 |
|
| 476 |
if (kwds != NULL && PyDict_Size(kwds) > 0) { |
| 477 |
PyErr_SetString(PyExc_TypeError, |
| 478 |
"Lock() takes no keyword arguments"); |
| 479 |
return -1; |
| 480 |
} |
| 481 |
|
| 482 |
return 0; |
| 483 |
} |
| 484 |
|
| 485 |
static void |
| 486 |
Lock_dealloc(LockObject *self) |
| 487 |
{ |
| 488 |
#if defined(LOCK_BACKEND_SEM) |
| 489 |
sem_destroy(&self->sem); |
| 490 |
#elif defined(LOCK_BACKEND_PTHREAD) |
| 491 |
// `mut` is only ever held transiently within a single call, so it is |
| 492 |
// always unlocked here even if the Python lock is still "locked". |
| 493 |
// Some pthread implementations require the cond to be destroyed first. |
| 494 |
pthread_cond_destroy(&self->lock_released); |
| 495 |
pthread_mutex_destroy(&self->mut); |
| 496 |
#endif |
| 497 |
Py_TYPE(self)->tp_free((PyObject *)self); |
| 498 |
} |
| 499 |
|
| 500 |
static PyObject * |
| 501 |
Lock_acquire(LockObject *self, PyObject *const *args, Py_ssize_t nargs, |
| 502 |
PyObject *kwnames) |
| 503 |
{ |
| 504 |
int blocking = 1; |
| 505 |
|
| 506 |
Py_ssize_t nkw = kwnames ? PyTuple_GET_SIZE(kwnames) : 0; |
| 507 |
if (nargs + nkw > 1) { |
| 508 |
PyErr_SetString(PyExc_TypeError, "acquire() takes at most 1 argument"); |
| 509 |
return NULL; |
| 510 |
} |
| 511 |
|
| 512 |
if (nargs == 1) { |
| 513 |
blocking = PyObject_IsTrue(args[0]); |
| 514 |
if (blocking < 0) |
| 515 |
return NULL; |
| 516 |
} else if (nkw == 1) { |
| 517 |
PyObject *key = PyTuple_GET_ITEM(kwnames, 0); |
| 518 |
if (PyUnicode_CompareWithASCIIString(key, "blocking") != 0) { |
| 519 |
PyErr_Format(PyExc_TypeError, |
| 520 |
"acquire() got an unexpected keyword argument '%U'", |
| 521 |
key); |
| 522 |
return NULL; |
| 523 |
} |
| 524 |
blocking = PyObject_IsTrue(args[0]); |
| 525 |
if (blocking < 0) |
| 526 |
return NULL; |
| 527 |
} |
| 528 |
|
| 529 |
int result = Lock_acquire_impl(self, blocking); |
| 530 |
if (result < 0) { |
| 531 |
return NULL; |
| 532 |
} |
| 533 |
return PyBool_FromLong(result); |
| 534 |
} |
| 535 |
|
| 536 |
static PyObject * |
| 537 |
Lock_release(LockObject *self, PyObject *Py_UNUSED(ignored)) |
| 538 |
{ |
| 539 |
if (Lock_release_impl(self) < 0) { |
| 540 |
PyErr_SetString(PyExc_RuntimeError, "cannot release an unlocked lock"); |
| 541 |
return NULL; |
| 542 |
} |
| 543 |
Py_RETURN_NONE; |
| 544 |
} |
| 545 |
|
| 546 |
static PyObject * |
| 547 |
Lock_locked(LockObject *self, PyObject *Py_UNUSED(ignored)) |
| 548 |
{ |
| 549 |
return PyBool_FromLong(Lock_is_locked(self)); |
| 550 |
} |
| 551 |
|
| 552 |
static PyObject * |
| 553 |
Lock_enter(LockObject *self, PyObject *Py_UNUSED(ignored)) |
| 554 |
{ |
| 555 |
int result = Lock_acquire_impl(self, 1); |
| 556 |
if (result < 0) |
| 557 |
return NULL; |
| 558 |
return PyBool_FromLong(result); |
| 559 |
} |
| 560 |
|
| 561 |
static PyObject * |
| 562 |
Lock_exit(LockObject *self, PyObject *const *args, Py_ssize_t nargs) |
| 563 |
{ |
| 564 |
return Lock_release(self, NULL); |
| 565 |
} |
| 566 |
|
| 567 |
static PyMethodDef Lock_methods[] = { |
| 568 |
{"acquire", (PyCFunction)(void(*)(void))Lock_acquire, METH_FASTCALL | METH_KEYWORDS, |
| 569 |
PyDoc_STR("Acquire the lock, blocking or non-blocking.\n" |
| 570 |
"Returns True if the lock was acquired, False otherwise.")}, |
| 571 |
{"release", (PyCFunction)Lock_release, METH_NOARGS, |
| 572 |
PyDoc_STR("Release the lock.")}, |
| 573 |
{"locked", (PyCFunction)Lock_locked, METH_NOARGS, |
| 574 |
PyDoc_STR("Return True if the lock is currently held.")}, |
| 575 |
{"__enter__", (PyCFunction)Lock_enter, METH_NOARGS, |
| 576 |
PyDoc_STR("Acquire the lock.")}, |
| 577 |
{"__exit__", (PyCFunction)Lock_exit, METH_FASTCALL, |
| 578 |
PyDoc_STR("Release the lock.")}, |
| 579 |
{NULL} |
| 580 |
}; |
| 581 |
|
| 582 |
static PyTypeObject LockType = { |
| 583 |
.ob_base = PyVarObject_HEAD_INIT(NULL, 0) |
| 584 |
.tp_name = "Lock", |
| 585 |
.tp_doc = PyDoc_STR("A fast mutual exclusion lock"), |
| 586 |
.tp_basicsize = sizeof(LockObject), |
| 587 |
.tp_itemsize = 0, |
| 588 |
.tp_flags = Py_TPFLAGS_DEFAULT, |
| 589 |
.tp_new = Lock_new, |
| 590 |
.tp_init = (initproc)Lock_init, |
| 591 |
.tp_dealloc = (destructor)Lock_dealloc, |
| 592 |
.tp_methods = Lock_methods, |
| 593 |
}; |
| 594 |
|
| 595 |
static PyTypeObject * |
| 596 |
Lock_type_internal(void) { |
| 597 |
return &LockType; |
| 598 |
} |
| 599 |
|
| 600 |
// Create a new Lock object (for use from compiled code) |
| 601 |
static PyObject * |
| 602 |
Lock_new_internal(void) { |
| 603 |
LockObject *self = (LockObject *)LockType.tp_alloc(&LockType, 0); |
| 604 |
if (self != NULL && Lock_init_internal(self) < 0) { |
| 605 |
LockType.tp_free((PyObject *)self); |
| 606 |
return NULL; |
| 607 |
} |
| 608 |
return (PyObject *)self; |
| 609 |
} |
| 610 |
|
| 611 |
// Acquire the lock (blocking), for use from compiled code. |
| 612 |
// Returns true on success, sets error and returns 2 (ERR_MAGIC) on failure. |
| 613 |
static char |
| 614 |
Lock_acquire_internal(PyObject *self) { |
| 615 |
int result = Lock_acquire_impl((LockObject *)self, 1); |
| 616 |
if (result < 0) { |
| 617 |
return 2; |
| 618 |
} |
| 619 |
return (char)result; |
| 620 |
} |
| 621 |
|
| 622 |
// Acquire the lock with explicit blocking arg, for use from compiled code. |
| 623 |
// Returns true if acquired, false otherwise. Sets error and returns 2 |
| 624 |
// (ERR_MAGIC) on failure. |
| 625 |
static char |
| 626 |
Lock_acquire_blocking_internal(PyObject *self, char blocking) { |
| 627 |
int result = Lock_acquire_impl((LockObject *)self, blocking); |
| 628 |
if (result < 0) { |
| 629 |
return 2; |
| 630 |
} |
| 631 |
return (char)result; |
| 632 |
} |
| 633 |
|
| 634 |
// Release the lock, for use from compiled code. |
| 635 |
// Returns 0 (None) on success, sets error and returns 2 (ERR_MAGIC) on failure. |
| 636 |
static char |
| 637 |
Lock_release_internal(PyObject *self) { |
| 638 |
if (Lock_release_impl((LockObject *)self) < 0) { |
| 639 |
PyErr_SetString(PyExc_RuntimeError, "cannot release an unlocked lock"); |
| 640 |
return 2; |
| 641 |
} |
| 642 |
return 0; |
| 643 |
} |
| 644 |
|
| 645 |
// Check if the lock is held, for use from compiled code. |
| 646 |
static char |
| 647 |
Lock_locked_internal(PyObject *self) { |
| 648 |
return (char)Lock_is_locked((LockObject *)self); |
| 649 |
} |
| 650 |
|
| 651 |
static PyMethodDef librt_threading_module_methods[] = { |
| 652 |
{NULL, NULL, 0, NULL} |
| 653 |
}; |
| 654 |
|
| 655 |
static int |
| 656 |
threading_abi_version(void) { |
| 657 |
return LIBRT_THREADING_ABI_VERSION; |
| 658 |
} |
| 659 |
|
| 660 |
static int |
| 661 |
threading_api_version(void) { |
| 662 |
return LIBRT_THREADING_API_VERSION; |
| 663 |
} |
| 664 |
|
| 665 |
static int |
| 666 |
librt_threading_module_exec(PyObject *m) |
| 667 |
{ |
| 668 |
if (PyType_Ready(&LockType) < 0) { |
| 669 |
return -1; |
| 670 |
} |
| 671 |
if (PyModule_AddObjectRef(m, "Lock", (PyObject *)&LockType) < 0) { |
| 672 |
return -1; |
| 673 |
} |
| 674 |
|
| 675 |
// Export mypyc internal C API via capsule |
| 676 |
static void *threading_api[LIBRT_THREADING_API_LEN] = { |
| 677 |
(void *)threading_abi_version, |
| 678 |
(void *)threading_api_version, |
| 679 |
(void *)Lock_type_internal, |
| 680 |
(void *)Lock_new_internal, |
| 681 |
(void *)Lock_acquire_internal, |
| 682 |
(void *)Lock_release_internal, |
| 683 |
(void *)Lock_locked_internal, |
| 684 |
(void *)Lock_acquire_blocking_internal, |
| 685 |
}; |
| 686 |
PyObject *c_api_object = PyCapsule_New((void *)threading_api, "librt.threading._C_API", NULL); |
| 687 |
if (PyModule_Add(m, "_C_API", c_api_object) < 0) { |
| 688 |
return -1; |
| 689 |
} |
| 690 |
return 0; |
| 691 |
} |
| 692 |
|
| 693 |
static PyModuleDef_Slot librt_threading_module_slots[] = { |
| 694 |
{Py_mod_exec, librt_threading_module_exec}, |
| 695 |
#ifdef Py_MOD_GIL_NOT_USED |
| 696 |
{Py_mod_gil, Py_MOD_GIL_NOT_USED}, |
| 697 |
#endif |
| 698 |
{0, NULL} |
| 699 |
}; |
| 700 |
|
| 701 |
static PyModuleDef librt_threading_module = { |
| 702 |
.m_base = PyModuleDef_HEAD_INIT, |
| 703 |
.m_name = "threading", |
| 704 |
.m_doc = "Fast threading primitives optimized for mypyc", |
| 705 |
.m_size = 0, |
| 706 |
.m_methods = librt_threading_module_methods, |
| 707 |
.m_slots = librt_threading_module_slots, |
| 708 |
}; |
| 709 |
|
| 710 |
PyMODINIT_FUNC |
| 711 |
PyInit_threading(void) |
| 712 |
{ |
| 713 |
return PyModuleDef_Init(&librt_threading_module); |
| 714 |
} |