Skip to content

Commit dd30f16

Browse files
gh-141563: make PyDateTime_IMPORT thread-safe (#144210)
1 parent d99f3fc commit dd30f16

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

Include/datetime.h

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,23 @@ typedef struct {
196196
/* Define global variable for the C API and a macro for setting it. */
197197
static PyDateTime_CAPI *PyDateTimeAPI = NULL;
198198

199-
#define PyDateTime_IMPORT \
200-
PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0)
199+
static inline PyDateTime_CAPI *
200+
_PyDateTime_IMPORT(void) {
201+
PyDateTime_CAPI *val = _Py_atomic_load_ptr(&PyDateTimeAPI);
202+
if (val == NULL) {
203+
PyDateTime_CAPI *capi = (PyDateTime_CAPI *)PyCapsule_Import(
204+
PyDateTime_CAPSULE_NAME, 0);
205+
if (capi != NULL) {
206+
/* if the compare exchange fails then in that case
207+
another thread would have initialized it */
208+
_Py_atomic_compare_exchange_ptr(&PyDateTimeAPI, &val, (void *)capi);
209+
return capi;
210+
}
211+
}
212+
return val;
213+
}
214+
215+
#define PyDateTime_IMPORT _PyDateTime_IMPORT()
201216

202217
/* Macro for access to the UTC singleton */
203218
#define PyDateTime_TimeZone_UTC PyDateTimeAPI->TimeZone_UTC
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix thread safety of :c:macro:`! PyDateTime_IMPORT`.

0 commit comments

Comments
 (0)