Skip to content

Commit 7f01183

Browse files
pybind11_protobuf authorscopybara-github
authored andcommitted
Use pybind11::gil_safe_call_once_and_store for thread-safe singleton initialization.
PiperOrigin-RevId: 823652079
1 parent 87ec9af commit 7f01183

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

pybind11_protobuf/proto_cast_util.cc

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
#include <Python.h>
44
#include <pybind11/cast.h>
5+
#include <pybind11/gil_safe_call_once.h>
56
#include <pybind11/pybind11.h>
67
#include <pybind11/pytypes.h>
78

@@ -150,8 +151,12 @@ class GlobalState {
150151
// due to order of destruction conflict with python threads. See
151152
// https://github.com/pybind/pybind11/issues/1598
152153
static GlobalState* instance() {
153-
static auto instance = new GlobalState();
154-
return instance;
154+
PYBIND11_CONSTINIT static pybind11::gil_safe_call_once_and_store<
155+
GlobalState*>
156+
storage;
157+
return storage
158+
.call_once_and_store_result([]() { return new GlobalState(); })
159+
.get_stored();
155160
}
156161

157162
py::handle global_pool() { return global_pool_; }

0 commit comments

Comments
 (0)