Skip to content

Commit 0e59958

Browse files
laramielpre-commit-ci[bot]Skylion007
authored
Fix thread safety for pybind11 loader_life_support (#3237)
* Fix thread safety for pybind11 loader_life_support Fixes issue: #2765 This converts the vector of PyObjects to either a single void* or a per-thread void* depending on the WITH_THREAD define. The new field is used by each thread to construct a stack of loader_life_support frames that can extend the life of python objects. The pointer is updated when the loader_life_support object is allocated (which happens before a call) as well as on release. Each loader_life_support maintains a set of PyObject references that need to be lifetime extended; this is done by storing them in a c++ std::unordered_set and clearing the references when the method completes. * Also update the internals version as the internal struct is no longer compatible * Add test demonstrating threading works correctly. It may be appropriate to run this under msan/tsan/etc. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update test to use lifetime-extended references rather than std::string_view, as that's a C++ 17 feature. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Make loader_life_support members private * Update version to dev2 * Update test to use python threading rather than concurrent.futures * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Remove unnecessary env in test * Remove unnecessary pytest in test * Use native C++ thread_local in place of python per-thread data structures to retain compatability * clang-format test_thread.cpp * Add a note about debugging the py::cast() error * thread_test.py now propagates exceptions on join() calls. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * remove unused sys / merge * Update include order in test_thread.cpp * Remove spurious whitespace * Update comment / whitespace. * Address review comments * lint cleanup * Fix test IntStruct constructor. * Add explicit to constructor Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Aaron Gokaslan <[email protected]>
1 parent 121b91f commit 0e59958

File tree

7 files changed

+148
-30
lines changed

7 files changed

+148
-30
lines changed

include/pybind11/detail/common.h

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@
1111

1212
#define PYBIND11_VERSION_MAJOR 2
1313
#define PYBIND11_VERSION_MINOR 8
14-
#define PYBIND11_VERSION_PATCH 0.dev1
14+
#define PYBIND11_VERSION_PATCH 0.dev2
1515

1616
// Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
1717
// Additional convention: 0xD = dev
18-
#define PYBIND11_VERSION_HEX 0x020800D1
18+
#define PYBIND11_VERSION_HEX 0x020800D2
1919

2020
#define PYBIND11_NAMESPACE_BEGIN(name) namespace name {
2121
#define PYBIND11_NAMESPACE_END(name) }

include/pybind11/detail/internals.h

+3-3
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ struct internals {
106106
std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
107107
std::forward_list<ExceptionTranslator> registered_exception_translators;
108108
std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
109-
std::vector<PyObject *> loader_patient_stack; // Used by `loader_life_support`
109+
std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
110110
std::forward_list<std::string> static_strings; // Stores the std::strings backing detail::c_str()
111111
PyTypeObject *static_property_type;
112112
PyTypeObject *default_metaclass;
@@ -298,12 +298,12 @@ PYBIND11_NOINLINE internals &get_internals() {
298298
#if PY_VERSION_HEX >= 0x03070000
299299
internals_ptr->tstate = PyThread_tss_alloc();
300300
if (!internals_ptr->tstate || (PyThread_tss_create(internals_ptr->tstate) != 0))
301-
pybind11_fail("get_internals: could not successfully initialize the TSS key!");
301+
pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
302302
PyThread_tss_set(internals_ptr->tstate, tstate);
303303
#else
304304
internals_ptr->tstate = PyThread_create_key();
305305
if (internals_ptr->tstate == -1)
306-
pybind11_fail("get_internals: could not successfully initialize the TLS key!");
306+
pybind11_fail("get_internals: could not successfully initialize the tstate TLS key!");
307307
PyThread_set_key_value(internals_ptr->tstate, tstate);
308308
#endif
309309
internals_ptr->istate = tstate->interp;

include/pybind11/detail/type_caster_base.h

+31-24
Original file line numberDiff line numberDiff line change
@@ -31,47 +31,54 @@ PYBIND11_NAMESPACE_BEGIN(detail)
3131
/// A life support system for temporary objects created by `type_caster::load()`.
3232
/// Adding a patient will keep it alive up until the enclosing function returns.
3333
class loader_life_support {
34+
private:
35+
loader_life_support* parent = nullptr;
36+
std::unordered_set<PyObject *> keep_alive;
37+
38+
static loader_life_support** get_stack_pp() {
39+
#if defined(WITH_THREAD)
40+
thread_local static loader_life_support* per_thread_stack = nullptr;
41+
return &per_thread_stack;
42+
#else
43+
static loader_life_support* global_stack = nullptr;
44+
return &global_stack;
45+
#endif
46+
}
47+
3448
public:
3549
/// A new patient frame is created when a function is entered
3650
loader_life_support() {
37-
get_internals().loader_patient_stack.push_back(nullptr);
51+
loader_life_support** stack = get_stack_pp();
52+
parent = *stack;
53+
*stack = this;
3854
}
3955

4056
/// ... and destroyed after it returns
4157
~loader_life_support() {
42-
auto &stack = get_internals().loader_patient_stack;
43-
if (stack.empty())
58+
loader_life_support** stack = get_stack_pp();
59+
if (*stack != this)
4460
pybind11_fail("loader_life_support: internal error");
45-
46-
auto ptr = stack.back();
47-
stack.pop_back();
48-
Py_CLEAR(ptr);
49-
50-
// A heuristic to reduce the stack's capacity (e.g. after long recursive calls)
51-
if (stack.capacity() > 16 && !stack.empty() && stack.capacity() / stack.size() > 2)
52-
stack.shrink_to_fit();
61+
*stack = parent;
62+
for (auto* item : keep_alive)
63+
Py_DECREF(item);
5364
}
5465

5566
/// This can only be used inside a pybind11-bound function, either by `argument_loader`
5667
/// at argument preparation time or by `py::cast()` at execution time.
5768
PYBIND11_NOINLINE static void add_patient(handle h) {
58-
auto &stack = get_internals().loader_patient_stack;
59-
if (stack.empty())
69+
loader_life_support* frame = *get_stack_pp();
70+
if (!frame) {
71+
// NOTE: It would be nice to include the stack frames here, as this indicates
72+
// use of pybind11::cast<> outside the normal call framework, finding such
73+
// a location is challenging. Developers could consider printing out
74+
// stack frame addresses here using something like __builtin_frame_address(0)
6075
throw cast_error("When called outside a bound function, py::cast() cannot "
6176
"do Python -> C++ conversions which require the creation "
6277
"of temporary values");
63-
64-
auto &list_ptr = stack.back();
65-
if (list_ptr == nullptr) {
66-
list_ptr = PyList_New(1);
67-
if (!list_ptr)
68-
pybind11_fail("loader_life_support: error allocating list");
69-
PyList_SET_ITEM(list_ptr, 0, h.inc_ref().ptr());
70-
} else {
71-
auto result = PyList_Append(list_ptr, h.ptr());
72-
if (result == -1)
73-
pybind11_fail("loader_life_support: error adding patient");
7478
}
79+
80+
if (frame->keep_alive.insert(h.ptr()).second)
81+
Py_INCREF(h.ptr());
7582
}
7683
};
7784

pybind11/_version.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ def _to_int(s):
88
return s
99

1010

11-
__version__ = "2.8.0.dev1"
11+
__version__ = "2.8.0.dev2"
1212
version_info = tuple(_to_int(s) for s in __version__.split("."))

tests/CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ set(PYBIND11_TEST_FILES
129129
test_stl.cpp
130130
test_stl_binders.cpp
131131
test_tagbased_polymorphic.cpp
132+
test_thread.cpp
132133
test_union.cpp
133134
test_virtual_functions.cpp)
134135

tests/test_thread.cpp

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
tests/test_thread.cpp -- call pybind11 bound methods in threads
3+
4+
Copyright (c) 2021 Laramie Leavitt (Google LLC) <[email protected]>
5+
6+
All rights reserved. Use of this source code is governed by a
7+
BSD-style license that can be found in the LICENSE file.
8+
*/
9+
10+
#include <pybind11/cast.h>
11+
#include <pybind11/pybind11.h>
12+
13+
#include <chrono>
14+
#include <thread>
15+
16+
#include "pybind11_tests.h"
17+
18+
namespace py = pybind11;
19+
20+
namespace {
21+
22+
struct IntStruct {
23+
explicit IntStruct(int v) : value(v) {};
24+
~IntStruct() { value = -value; }
25+
IntStruct(const IntStruct&) = default;
26+
IntStruct& operator=(const IntStruct&) = default;
27+
28+
int value;
29+
};
30+
31+
} // namespace
32+
33+
TEST_SUBMODULE(thread, m) {
34+
35+
py::class_<IntStruct>(m, "IntStruct").def(py::init([](const int i) { return IntStruct(i); }));
36+
37+
// implicitly_convertible uses loader_life_support when an implicit
38+
// conversion is required in order to lifetime extend the reference.
39+
//
40+
// This test should be run with ASAN for better effectiveness.
41+
py::implicitly_convertible<int, IntStruct>();
42+
43+
m.def("test", [](int expected, const IntStruct &in) {
44+
{
45+
py::gil_scoped_release release;
46+
std::this_thread::sleep_for(std::chrono::milliseconds(5));
47+
}
48+
49+
if (in.value != expected) {
50+
throw std::runtime_error("Value changed!!");
51+
}
52+
});
53+
54+
m.def(
55+
"test_no_gil",
56+
[](int expected, const IntStruct &in) {
57+
std::this_thread::sleep_for(std::chrono::milliseconds(5));
58+
if (in.value != expected) {
59+
throw std::runtime_error("Value changed!!");
60+
}
61+
},
62+
py::call_guard<py::gil_scoped_release>());
63+
64+
// NOTE: std::string_view also uses loader_life_support to ensure that
65+
// the string contents remain alive, but that's a C++ 17 feature.
66+
}

tests/test_thread.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import threading
4+
5+
from pybind11_tests import thread as m
6+
7+
8+
class Thread(threading.Thread):
9+
def __init__(self, fn):
10+
super(Thread, self).__init__()
11+
self.fn = fn
12+
self.e = None
13+
14+
def run(self):
15+
try:
16+
for i in range(10):
17+
self.fn(i, i)
18+
except Exception as e:
19+
self.e = e
20+
21+
def join(self):
22+
super(Thread, self).join()
23+
if self.e:
24+
raise self.e
25+
26+
27+
def test_implicit_conversion():
28+
a = Thread(m.test)
29+
b = Thread(m.test)
30+
c = Thread(m.test)
31+
for x in [a, b, c]:
32+
x.start()
33+
for x in [c, b, a]:
34+
x.join()
35+
36+
37+
def test_implicit_conversion_no_gil():
38+
a = Thread(m.test_no_gil)
39+
b = Thread(m.test_no_gil)
40+
c = Thread(m.test_no_gil)
41+
for x in [a, b, c]:
42+
x.start()
43+
for x in [c, b, a]:
44+
x.join()

0 commit comments

Comments
 (0)