Skip to content

Commit c3f4649

Browse files
make PyDateTime_IMPORT thread-safe
1 parent ca99bfd commit c3f4649

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

Include/datetime.h

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,18 @@ typedef struct {
197197
static PyDateTime_CAPI *PyDateTimeAPI = NULL;
198198

199199
#define PyDateTime_IMPORT \
200-
PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0)
200+
do { \
201+
void *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+
/* it is okay if the compare exchange fails as in that case
207+
another thread would have initialized it */ \
208+
_Py_atomic_compare_exchange_ptr(&PyDateTimeAPI, &val, (void *)capi); \
209+
} \
210+
} \
211+
} while (0)
201212

202213
/* Macro for access to the UTC singleton */
203214
#define PyDateTime_TimeZone_UTC PyDateTimeAPI->TimeZone_UTC

0 commit comments

Comments
 (0)