From 715ca752ac4f8ba69fe68110823e0eabf5614bc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Storsj=C3=B6?= Date: Wed, 7 Jul 2021 21:06:08 +0000 Subject: [PATCH] [libcxx] [test] Fix spurious failures in the thread detach test on Windows Make sure that the detached thread has started up before exiting the process. If the detached thread hasn't started up at all, and the main thread exits, global data structures in the process are torn down, which then can cause crashes when the thread starts up late after required mutexes have been destroyed. (In particular, the mutex used internally in _Init_thread_header, which is used in the initialization of __thread_local_data()::__p, can cause crashes if the main thread already has finished and progressed far with destruction.) Differential Revision: https://reviews.llvm.org/D105592 --- .../thread.thread.member/detach.pass.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libcxx/test/std/thread/thread.threads/thread.thread.class/thread.thread.member/detach.pass.cpp b/libcxx/test/std/thread/thread.threads/thread.thread.class/thread.thread.member/detach.pass.cpp index ea82d5392aeb..03dc79d2d837 100644 --- a/libcxx/test/std/thread/thread.threads/thread.thread.class/thread.thread.member/detach.pass.cpp +++ b/libcxx/test/std/thread/thread.threads/thread.thread.class/thread.thread.member/detach.pass.cpp @@ -60,7 +60,7 @@ public: int G::n_alive = 0; bool G::op_run = false; -void foo() {} +void foo() { done = true; } int main(int, char**) { @@ -75,6 +75,7 @@ int main(int, char**) assert(G::n_alive == 1); } assert(G::n_alive == 0); + done = false; #ifndef TEST_HAS_NO_EXCEPTIONS { std::thread t0 = support::make_test_thread(foo); @@ -85,6 +86,11 @@ int main(int, char**) t0.detach(); } catch (std::system_error const&) { } + // Wait to make sure that the detached thread has started up. + // Without this, we could exit main and start destructing global + // resources that are needed when the thread starts up, while the + // detached thread would start up only later. + while (!done) {} } #endif