Skip to content

Commit 48b06f9

Browse files
committed
double-check datetime init
1 parent 1e84d7b commit 48b06f9

1 file changed

Lines changed: 9 additions & 7 deletions

File tree

pyo3-ffi/src/datetime.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -611,10 +611,7 @@ pub unsafe fn PyDateTimeAPI() -> *mut PyDateTime_CAPI {
611611
pub unsafe fn PyDateTime_IMPORT() {
612612
// Protect against race conditions when the datetime API is concurrently
613613
// initialized in multiple threads.
614-
if PyDateTimeAPI_impl
615-
.already_called
616-
.swap(true, Ordering::SeqCst)
617-
{
614+
if PyDateTimeAPI_impl.already_set.load(Ordering::SeqCst) {
618615
return;
619616
}
620617

@@ -631,7 +628,12 @@ pub unsafe fn PyDateTime_IMPORT() {
631628
return;
632629
}
633630

634-
*PyDateTimeAPI_impl.ptr.get() = py_datetime_c_api;
631+
// Protect against race conditions when the datetime API is concurrently
632+
// initialized in multiple threads. UnsafeCell.get() cannot panic so this
633+
// won't panic either.
634+
if !PyDateTimeAPI_impl.already_set.swap(true, Ordering::SeqCst) {
635+
*PyDateTimeAPI_impl.ptr.get() = py_datetime_c_api;
636+
}
635637
}
636638

637639
#[inline]
@@ -842,12 +844,12 @@ extern_libpython! {
842844
// Rust specific implementation details
843845

844846
struct PyDateTimeAPISingleton {
845-
already_called: AtomicBool,
847+
already_set: AtomicBool,
846848
ptr: UnsafeCell<*mut PyDateTime_CAPI>,
847849
}
848850
unsafe impl Sync for PyDateTimeAPISingleton {}
849851

850852
static PyDateTimeAPI_impl: PyDateTimeAPISingleton = PyDateTimeAPISingleton {
851-
already_called: AtomicBool::new(false),
853+
already_set: AtomicBool::new(false),
852854
ptr: UnsafeCell::new(ptr::null_mut()),
853855
};

0 commit comments

Comments
 (0)