1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // UNSUPPORTED: libcpp-has-no-threads 11 12 // <thread> 13 14 // class thread 15 16 // void detach(); 17 18 #include <thread> 19 #include <atomic> 20 #include <system_error> 21 #include <cassert> 22 23 #include "test_macros.h" 24 25 std::atomic_bool done(false); 26 27 class G 28 { 29 int alive_; 30 bool done_; 31 public: 32 static int n_alive; 33 static bool op_run; 34 G()35 G() : alive_(1), done_(false) 36 { 37 ++n_alive; 38 } 39 G(const G & g)40 G(const G& g) : alive_(g.alive_), done_(false) 41 { 42 ++n_alive; 43 } ~G()44 ~G() 45 { 46 alive_ = 0; 47 --n_alive; 48 if (done_) done = true; 49 } 50 operator ()()51 void operator()() 52 { 53 assert(alive_ == 1); 54 assert(n_alive >= 1); 55 op_run = true; 56 done_ = true; 57 } 58 }; 59 60 int G::n_alive = 0; 61 bool G::op_run = false; 62 foo()63void foo() {} 64 main()65int main() 66 { 67 { 68 G g; 69 std::thread t0(g); 70 assert(t0.joinable()); 71 t0.detach(); 72 assert(!t0.joinable()); 73 while (!done) {} 74 assert(G::op_run); 75 assert(G::n_alive == 1); 76 } 77 assert(G::n_alive == 0); 78 #ifndef TEST_HAS_NO_EXCEPTIONS 79 { 80 std::thread t0(foo); 81 assert(t0.joinable()); 82 t0.detach(); 83 assert(!t0.joinable()); 84 try { 85 t0.detach(); 86 } catch (std::system_error const&) { 87 } 88 } 89 #endif 90 } 91