[PATCH] libstdc++: Fix race in std::thread::join() self-join test [PR128548]
Michele Dionisio
michele.dionisio@gmail.com
Sat Nov 21 09:17:06 GMT 2026
The new thread calls t.join() while the main thread may still be
move-assigning the new std::thread object to t. When the new thread
runs first it sees an empty t, join() fails with EINVAL instead of
EDEADLK and the assertion fails. This happens a few times every
thousand runs on a loaded machine, and always under ThreadSanitizer.
Make the new thread wait for the assignment using a mutex held by the
main thread until t has been assigned.
libstdc++-v3/ChangeLog:
PR libstdc++/128548
* testsuite/30_threads/thread/members/128548.cc: Do not read t
in the new thread before it has been assigned.
Signed-off-by: Michele Dionisio <michele.dionisio@gmail.com>
---
Tested on x86_64-pc-linux-gnu with a bootstrapped compiler at
828297e35da (the test is unchanged on current trunk).
Without the patch the execution test fails between 6 and 122 times in
2000 runs, depending on the load of the machine, and every time when
built with -fsanitize=thread. With the patch it passed 2000 runs, and
it passes with GLIBCXX_TESTSUITE_STDS=11,14,17,20,23,26.
OK for trunk?
.../30_threads/thread/members/128548.cc | 28 ++++++++++++-------
1 file changed, 18 insertions(+), 10 deletions(-)
diff --git a/libstdc++-v3/testsuite/30_threads/thread/members/128548.cc b/libstdc++-v3/testsuite/30_threads/thread/members/128548.cc
index 86a7e63c809..7114b55520d 100644
--- a/libstdc++-v3/testsuite/30_threads/thread/members/128548.cc
+++ b/libstdc++-v3/testsuite/30_threads/thread/members/128548.cc
@@ -5,23 +5,31 @@
// Bug 128548 - std::thread::join should check to make sure id is not self
#include <thread>
+#include <mutex>
#include <system_error>
#include <testsuite_hooks.h>
int main()
{
std::error_code ec;
+ std::mutex m;
std::thread t;
- t = std::thread{ [&] {
- try
- {
- t.join();
- }
- catch (const std::system_error& e)
- {
- ec = e.code();
- }
- }};
+ {
+ // Hold the lock until t has been assigned, the new thread must not
+ // read t before that.
+ std::lock_guard<std::mutex> l(m);
+ t = std::thread{ [&] {
+ std::lock_guard<std::mutex> l(m);
+ try
+ {
+ t.join();
+ }
+ catch (const std::system_error& e)
+ {
+ ec = e.code();
+ }
+ }};
+ }
t.join();
VERIFY( ec == std::errc::resource_deadlock_would_occur );
}
--
2.43.0
More information about the Libstdc++
mailing list