Skip to content

Commit 1ce2715

Browse files
committed
Replace comments:
Document PRECONDITION. Adopt comment suggested by @tkoeppe: #4877 (comment)
1 parent 88cec11 commit 1ce2715

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

include/pybind11/numpy.h

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,18 @@ PYBIND11_NAMESPACE_BEGIN(detail)
4747
template <typename T>
4848
class LazyInitializeAtLeastOnceDestroyNever {
4949
public:
50+
// PRECONDITION: The GIL must be held when `Get()` is called.
51+
// It is possible that multiple threads execute `Get()` with `initialized_`
52+
// still being false, and thus proceed to execute `initialize()`. This can
53+
// happen if `initialize()` releases and reacquires the GIL internally.
54+
// We accept this, and expect the operation to be both idempotent and cheap.
5055
template <typename Initialize>
5156
T &Get(Initialize &&initialize) {
5257
if (!initialized_) {
5358
assert(PyGILState_Check());
54-
// Multiple threads may run this concurrently, but that is fine.
55-
auto value = initialize(); // May release and re-acquire the GIL.
56-
if (!initialized_) { // This runs with the GIL held,
57-
new // therefore this is reached only once.
58-
(reinterpret_cast<T *>(value_storage_)) T(std::move(value));
59+
auto value = initialize();
60+
if (!initialized_) {
61+
new (reinterpret_cast<T *>(value_storage_)) T(std::move(value));
5962
initialized_ = true;
6063
}
6164
}

0 commit comments

Comments
 (0)