Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add pybind11/gil_safe_call_once.h (to fix deadlocks in pybind11/numpy.h) #4877

Merged
merged 31 commits into from
Oct 12, 2023
Merged
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
38317c3
LazyInitializeAtLeastOnceDestroyNever v1
Oct 9, 2023
e7b8c4f
Go back to using `union` as originally suggested by jbms@. The trick …
Oct 9, 2023
74ac0d9
Revert "Go back to using `union` as originally suggested by jbms@. Th…
Oct 9, 2023
109a165
Remove `#include <stdalign.h>`
Oct 9, 2023
88cec11
Suppress gcc 4.8.5 (CentOS 7) warning.
Oct 9, 2023
1ce2715
Replace comments:
Oct 9, 2023
e7be9c2
Adopt suggestion by @tkoeppe:
Oct 9, 2023
f07b28b
Add `PYBIND11_CONSTINIT`, but it does not work for the current use ca…
Oct 9, 2023
36be645
Revert "Add `PYBIND11_CONSTINIT`, but it does not work for the curren…
Oct 9, 2023
7bc16a6
Reapply "Add `PYBIND11_CONSTINIT`, but it does not work for the curre…
Oct 9, 2023
78f4e93
Add Default Member Initializer on `value_storage_` as suggested by @t…
Oct 9, 2023
6d9441d
Fix copy-paste-missed-a-change mishap in commit 88cec1152ab5576db19ba…
Oct 9, 2023
a864f21
Semi-paranoid placement new (based on https://github.com/pybind/pybin…
Oct 9, 2023
6689b06
Move PYBIND11_CONSTINIT to detail/common.h
Oct 9, 2023
d965f29
Move code to the right places, rename new class and some variables.
Oct 9, 2023
398a42c
Fix oversight: update tests/extra_python_package/test_files.py
Oct 9, 2023
ab2cf8e
Get the name right first.
Oct 9, 2023
6d5bdd8
Use `std::call_once`, `std::atomic`, following a pattern developed by…
Oct 9, 2023
4c5dd1b
Make the API more self-documenting (and possibly more easily reusable).
Oct 9, 2023
8633c5b
google-clang-tidy IWYU fixes
Oct 9, 2023
82f3efc
Rewrite comment as suggested by @tkoeppe
Oct 10, 2023
3ebd139
Update test_exceptions.cpp and exceptions.rst
Oct 10, 2023
c33712d
Fix oversight in previous commit: add `PYBIND11_CONSTINIT`
Oct 10, 2023
dcf2b92
Make `get_stored()` non-const for simplicity.
Oct 10, 2023
4557dce
Add comment regarding `KeyboardInterrupt` behavior, based heavily on …
Oct 10, 2023
704fe13
Add `assert(PyGILState_Check())` in `gil_scoped_release` ctor (simple…
Oct 10, 2023
b2f87a8
Fix oversight in previous commit (missing include cassert).
Oct 10, 2023
fad1017
Remove use of std::atomic, leaving comments with rationale, why it is…
Oct 10, 2023
8453302
Rewrite comment re `std:optional` based on deeper reflection (aka 2nd…
Oct 10, 2023
66bbc67
Additional comment with the conclusion of a discussion under PR #4877.
Oct 11, 2023
7cd9390
Small comment changes suggested by @tkoeppe.
Oct 11, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Remove use of std::atomic, leaving comments with rationale, why it is…
… not needed.
  • Loading branch information
Ralf W. Grosse-Kunstleve committed Oct 10, 2023
commit fad1017a08c2fd0f2df3901b3e2e3b08c8568990
19 changes: 12 additions & 7 deletions include/pybind11/gil_safe_call_once.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
#include "detail/common.h"
#include "gil.h"

#include <atomic>
#include <cassert>
#include <mutex>

Expand Down Expand Up @@ -49,21 +48,25 @@ class gil_safe_call_once_and_store {
// PRECONDITION: The GIL must be held when `call_once_and_store_result()` is called.
template <typename Callable>
gil_safe_call_once_and_store &call_once_and_store_result(Callable &&fn) {
if (!is_initialized_.load(std::memory_order_acquire)) {
gil_scoped_release gil_rel;
if (!is_initialized_) { // This read is guarded by the GIL.
// Multiple threads may enter here, because CPython API calls in the
// `fn()` call below may release and reacquire the GIL.
gil_scoped_release gil_rel; // Needed to establish lock ordering.
std::call_once(once_flag_, [&] {
// Only one thread will ever enter here.
gil_scoped_acquire gil_acq;
::new (storage_) T(fn());
is_initialized_.store(true, std::memory_order_release);
is_initialized_ = true; // This write is guarded by the GIL.
});
}
// Intentionally not returning `T &` to ensure the calling code is self-documenting.
return *this;
}

// This must only be called after `call_once_and_store()` was called.
// This must only be called after `call_once_and_store_result()` was called.
// Not const for simplicity. (Could be made const if there is an unforeseen need.)
T &get_stored() {
assert(is_initialized_.load(std::memory_order_relaxed));
assert(is_initialized_);
PYBIND11_WARNING_PUSH
#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
// Needed for gcc 4.8.5
Expand All @@ -77,9 +80,11 @@ class gil_safe_call_once_and_store {
PYBIND11_DTOR_CONSTEXPR ~gil_safe_call_once_and_store() = default;

private:
// `is_initialized_` below and `storage_` here can be replaced with `std::optional`
// when pybind11 drops C++11 support.
alignas(T) char storage_[sizeof(T)] = {};
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make this a std::optional and avoid both the atomic flag and the storage here.

You don't need the atomic since call_once is an inherent mutex that asserts ordering.

Copy link
Contributor

@tkoeppe tkoeppe Oct 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not the access inside the call_once that the atomic is for, but rather, the earlier access (the first check for the fast path).

However, I think you have a point that because we assume that the GIL is held on function entry, the boolean doesn't need to be atomic: the GIL serializes access to it (both read and write). The code with the atomic variable would work even without any external synchronisation, but since we already have the GIL on entry, I agree that we should be able to use a non-atomic boolean.

(And then the boolean + placement new could be replaced by std::optional, indeed.)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And just to make this point clearly: the first, outer boolean check provides a fast path on which we don't interact with the GIL any further. We only do the release and reacquire dance on the (hopefully rare) slow path.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Thomas! I'll definitely make the change to the simple bool then.

could be replaced by std::optional

Except that pybind11 still supports C++11, and std::optional was added only with C++17.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case leave it as bool + placement new :-)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, and also we do actually want the "constant-initializable, trivial destructible" behaviour of bool + placement new. Not only do we not want to destroy this object, but this also gives us cheaper static variables (no static guard, and no global destructructor list entry).

std::once_flag once_flag_ = {};
std::atomic<bool> is_initialized_ = {};
bool is_initialized_ = false;
};

PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
Loading