Skip to content

Commit ce2f005

Browse files
Fixed data race in all_type_info in free-threading mode (#5419)
* Fix data race all_type_info_populate in free-threading mode Description: - fixed data race all_type_info_populate in free-threading mode - added test For example, we have 2 threads entering `all_type_info`. Both enter `all_type_info_get_cache`` function and there is a first one which inserts a tuple (type, empty_vector) to the map and second is waiting. Inserting thread gets the (iter_to_key, True) and non-inserting thread after waiting gets (iter_to_key, False). Inserting thread than will add a weakref and will then call into `all_type_info_populate`. However, non-inserting thread is not entering `if (ins.second) {` clause and returns `ins.first->second;`` which is just empty_vector. Finally, non-inserting thread is failing the check in `allocate_layout`: ```c++ if (n_types == 0) { pybind11_fail( "instance allocation failed: new instance has no pybind11-registered base types"); } ``` * style: pre-commit fixes * Addressed PR comments --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent f46f5be commit ce2f005

File tree

5 files changed

+67
-12
lines changed

5 files changed

+67
-12
lines changed

include/pybind11/detail/type_caster_base.h

+1-8
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,6 @@ PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_
117117
for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {
118118
check.push_back((PyTypeObject *) parent.ptr());
119119
}
120-
121120
auto const &type_dict = get_internals().registered_types_py;
122121
for (size_t i = 0; i < check.size(); i++) {
123122
auto *type = check[i];
@@ -176,13 +175,7 @@ PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_
176175
* The value is cached for the lifetime of the Python type.
177176
*/
178177
inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
179-
auto ins = all_type_info_get_cache(type);
180-
if (ins.second) {
181-
// New cache entry: populate it
182-
all_type_info_populate(type, ins.first->second);
183-
}
184-
185-
return ins.first->second;
178+
return all_type_info_get_cache(type).first->second;
186179
}
187180

188181
/**

include/pybind11/pybind11.h

+11-4
Original file line numberDiff line numberDiff line change
@@ -2326,13 +2326,20 @@ keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
23262326
inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
23272327
all_type_info_get_cache(PyTypeObject *type) {
23282328
auto res = with_internals([type](internals &internals) {
2329-
return internals
2330-
.registered_types_py
2329+
auto ins = internals
2330+
.registered_types_py
23312331
#ifdef __cpp_lib_unordered_map_try_emplace
2332-
.try_emplace(type);
2332+
.try_emplace(type);
23332333
#else
2334-
.emplace(type, std::vector<detail::type_info *>());
2334+
.emplace(type, std::vector<detail::type_info *>());
23352335
#endif
2336+
if (ins.second) {
2337+
// For free-threading mode, this call must be under
2338+
// the with_internals() mutex lock, to avoid that other threads
2339+
// continue running with the empty ins.first->second.
2340+
all_type_info_populate(type, ins.first->second);
2341+
}
2342+
return ins;
23362343
});
23372344
if (res.second) {
23382345
// New cache entry created; set up a weak reference to automatically remove it if the type

tests/pybind11_tests.cpp

+5
Original file line numberDiff line numberDiff line change
@@ -128,4 +128,9 @@ PYBIND11_MODULE(pybind11_tests, m, py::mod_gil_not_used()) {
128128
for (const auto &initializer : initializers()) {
129129
initializer(m);
130130
}
131+
132+
py::class_<TestContext>(m, "TestContext")
133+
.def(py::init<>(&TestContext::createNewContextForInit))
134+
.def("__enter__", &TestContext::contextEnter)
135+
.def("__exit__", &TestContext::contextExit);
131136
}

tests/pybind11_tests.h

+21
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,24 @@ void ignoreOldStyleInitWarnings(F &&body) {
9696
)",
9797
py::dict(py::arg("body") = py::cpp_function(body)));
9898
}
99+
100+
// See PR #5419 for background.
101+
class TestContext {
102+
public:
103+
TestContext() = delete;
104+
TestContext(const TestContext &) = delete;
105+
TestContext(TestContext &&) = delete;
106+
static TestContext *createNewContextForInit() { return new TestContext("new-context"); }
107+
108+
pybind11::object contextEnter() {
109+
py::object contextObj = py::cast(*this);
110+
return contextObj;
111+
}
112+
void contextExit(const pybind11::object & /*excType*/,
113+
const pybind11::object & /*excVal*/,
114+
const pybind11::object & /*excTb*/) {}
115+
116+
private:
117+
explicit TestContext(const std::string &context) : context(context) {}
118+
std::string context;
119+
};

tests/test_class.py

+29
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import sys
34
from unittest import mock
45

56
import pytest
@@ -508,3 +509,31 @@ def test_pr4220_tripped_over_this():
508509
m.Empty0().get_msg()
509510
== "This is really only meant to exercise successful compilation."
510511
)
512+
513+
514+
@pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads")
515+
def test_all_type_info_multithreaded():
516+
# See PR #5419 for background.
517+
import threading
518+
519+
from pybind11_tests import TestContext
520+
521+
class Context(TestContext):
522+
pass
523+
524+
num_runs = 10
525+
num_threads = 4
526+
barrier = threading.Barrier(num_threads)
527+
528+
def func():
529+
barrier.wait()
530+
with Context():
531+
pass
532+
533+
for _ in range(num_runs):
534+
threads = [threading.Thread(target=func) for _ in range(num_threads)]
535+
for thread in threads:
536+
thread.start()
537+
538+
for thread in threads:
539+
thread.join()

0 commit comments

Comments
 (0)