Skip to content

Commit 43de801

Browse files
fix: make gil_safe_call_once thread-safe in free-threaded CPython (#5246)
* fix: Make gil_safe_call_once thread-safe in free-threaded CPython The "is_initialized_" flags is not protected by the GIL in free-threaded Python, so it needs to be an atomic field. Fixes #5245 * style: pre-commit fixes * Apply changes from code review --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent ccefee4 commit 43de801

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

include/pybind11/gil_safe_call_once.h

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@
88
#include <cassert>
99
#include <mutex>
1010

11+
#ifdef Py_GIL_DISABLED
12+
# include <atomic>
13+
#endif
14+
1115
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
1216

1317
// Use the `gil_safe_call_once_and_store` class below instead of the naive
@@ -82,7 +86,12 @@ class gil_safe_call_once_and_store {
8286
private:
8387
alignas(T) char storage_[sizeof(T)] = {};
8488
std::once_flag once_flag_ = {};
85-
bool is_initialized_ = false;
89+
#ifdef Py_GIL_DISABLED
90+
std::atomic_bool
91+
#else
92+
bool
93+
#endif
94+
is_initialized_{false};
8695
// The `is_initialized_`-`storage_` pair is very similar to `std::optional`,
8796
// but the latter does not have the triviality properties of former,
8897
// therefore `std::optional` is not a viable alternative here.

0 commit comments

Comments
 (0)