Skip to content

Commit f2c0ab8

Browse files
authored
Fix TSan warning in sub-interpreter test (#5729)
1 parent ad9180c commit f2c0ab8

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

include/pybind11/detail/internals.h

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -521,8 +521,11 @@ class internals_pp_manager {
521521
/// Drop all the references we're currently holding.
522522
void unref() {
523523
#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
524-
last_istate_.reset();
525-
internals_tls_p_.reset();
524+
if (get_num_interpreters_seen() > 1) {
525+
last_istate_.reset();
526+
internals_tls_p_.reset();
527+
return;
528+
}
526529
#endif
527530
internals_singleton_pp_ = nullptr;
528531
}

tests/test_embed/test_subinterpreter.cpp

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,21 @@ bool has_state_dict_internals_obj();
2020
uintptr_t get_details_as_uintptr();
2121

2222
void unsafe_reset_internals_for_single_interpreter() {
23-
// unsafe normally, but for subsequent tests, put this back.. we know there are no threads
24-
// running and only 1 interpreter
23+
// NOTE: This code is NOT SAFE unless the caller guarantees no other threads are alive
24+
// NOTE: This code is tied to the precise implementation of the internals holder
25+
26+
// first, unref the thread local internals
2527
py::detail::get_internals_pp_manager().unref();
2628
py::detail::get_local_internals_pp_manager().unref();
29+
30+
// we know there are no other interpreters, so we can lower this. SUPER DANGEROUS
2731
py::detail::get_num_interpreters_seen() = 1;
32+
33+
// now we unref the static global singleton internals
34+
py::detail::get_internals_pp_manager().unref();
35+
py::detail::get_local_internals_pp_manager().unref();
36+
37+
// finally, we reload the static global singleton
2838
py::detail::get_internals();
2939
py::detail::get_local_internals();
3040
}

0 commit comments

Comments
 (0)