https://gcc.gnu.org/g:aa042523ec421fdc3f461653582a738504e7c284
commit r17-6215-gaa042523ec421fdc3f461653582a738504e7c284 Author: Jonathan Wakely <[email protected]> Date: Mon Nov 9 16:32:29 2026 +0000 libstdc++: Add check for std::thread::join() on that thread [PR128548] POSIX says that pthread_join() is undefined if the calling thread tries to join itself. Our std::thread::join() does not check for this (possible because Glibc documents that it will be detected and an error reported). libstdc++-v3/ChangeLog: PR libstdc++/128548 * src/c++11/thread.cc (thread::join): Check for self-join. * testsuite/30_threads/thread/members/128548.cc: New test. Reviewed-by: Tomasz KamiĆski <[email protected]> Diff: --- libstdc++-v3/src/c++11/thread.cc | 8 +++++-- .../testsuite/30_threads/thread/members/128548.cc | 27 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/libstdc++-v3/src/c++11/thread.cc b/libstdc++-v3/src/c++11/thread.cc index 16b0d90d024b..881346428e81 100644 --- a/libstdc++-v3/src/c++11/thread.cc +++ b/libstdc++-v3/src/c++11/thread.cc @@ -129,9 +129,13 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION void thread::join() { - int __e = EINVAL; + int __e = 0; - if (_M_id != id()) + if (_M_id == this_thread::get_id()) + __e = EDEADLK; + else if (_M_id == id()) + __e = EINVAL; + else __e = __gthread_join(_M_id._M_thread, 0); if (__e) diff --git a/libstdc++-v3/testsuite/30_threads/thread/members/128548.cc b/libstdc++-v3/testsuite/30_threads/thread/members/128548.cc new file mode 100644 index 000000000000..86a7e63c8090 --- /dev/null +++ b/libstdc++-v3/testsuite/30_threads/thread/members/128548.cc @@ -0,0 +1,27 @@ +// { dg-do run { target c++11 } } +// { dg-additional-options "-pthread" { target pthread } } +// { dg-require-gthreads "" } + +// Bug 128548 - std::thread::join should check to make sure id is not self + +#include <thread> +#include <system_error> +#include <testsuite_hooks.h> + +int main() +{ + std::error_code ec; + std::thread t; + t = std::thread{ [&] { + try + { + t.join(); + } + catch (const std::system_error& e) + { + ec = e.code(); + } + }}; + t.join(); + VERIFY( ec == std::errc::resource_deadlock_would_occur ); +}
