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.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Michele Dionisio <[email protected]>
---
Changes since v1:
- Lock the mutex inside the try block in the new thread, as suggested
by Tomasz Kaminski <[email protected]>.
Tested on x86_64-pc-linux-gnu: the test passes with -std=gnu++11, 14,
17, 20, 23 and 26, passed 2000 runs in a row, and runs without data
races under -fsanitize=thread (the original test aborts there).
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 86a7e63c8090..71cf910421cd 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{ [&] {
+ try
+ {
+ std::lock_guard<std::mutex> l(m);
+ t.join();
+ }
+ catch (const std::system_error& e)
+ {
+ ec = e.code();
+ }
+ }};
+ }
t.join();
VERIFY( ec == std::errc::resource_deadlock_would_occur );
}
--
2.43.0