1695138caSHui //===----------------------------------------------------------------------===// 2695138caSHui // 3695138caSHui // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4695138caSHui // See https://llvm.org/LICENSE.txt for license information. 5695138caSHui // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6695138caSHui // 7695138caSHui //===----------------------------------------------------------------------===// 8695138caSHui // 9695138caSHui // UNSUPPORTED: no-threads 10695138caSHui // UNSUPPORTED: c++03, c++11, c++14, c++17 11695138caSHui // XFAIL: availability-synchronization_library-missing 12695138caSHui 13695138caSHui // void detach(); 14695138caSHui 15695138caSHui #include <atomic> 16695138caSHui #include <cassert> 17695138caSHui #include <chrono> 18695138caSHui #include <concepts> 19695138caSHui #include <functional> 20695138caSHui #include <optional> 21695138caSHui #include <system_error> 22695138caSHui #include <thread> 23695138caSHui #include <type_traits> 24695138caSHui 25*475e1543SLouis Dionne #include "make_test_thread.h" 26695138caSHui #include "test_macros.h" 27695138caSHui 28695138caSHui int main(int, char**) { 29695138caSHui // Effects: The thread represented by *this continues execution without the calling thread blocking. 30695138caSHui { 31695138caSHui std::atomic_bool start{false}; 32695138caSHui std::atomic_bool done{false}; 33*475e1543SLouis Dionne std::optional<std::jthread> jt = support::make_test_jthread([&start, &done] { 34695138caSHui start.wait(false); 35695138caSHui done = true; 36*475e1543SLouis Dionne }); 37695138caSHui 38695138caSHui // If it blocks, it will deadlock here 39695138caSHui jt->detach(); 40695138caSHui 41695138caSHui jt.reset(); 42695138caSHui 43695138caSHui // The other thread continues execution 44695138caSHui start = true; 45695138caSHui start.notify_all(); 46695138caSHui while (!done) { 47695138caSHui } 48695138caSHui } 49695138caSHui 50695138caSHui // Postconditions: get_id() == id(). 51695138caSHui { 52*475e1543SLouis Dionne std::jthread jt = support::make_test_jthread([] {}); 53695138caSHui assert(jt.get_id() != std::jthread::id()); 54695138caSHui jt.detach(); 55695138caSHui assert(jt.get_id() == std::jthread::id()); 56695138caSHui } 57695138caSHui 58695138caSHui #if !defined(TEST_HAS_NO_EXCEPTIONS) 59695138caSHui // Throws: system_error when an exception is required ([thread.req.exception]). 60695138caSHui // invalid_argument - if the thread is not joinable. 61695138caSHui { 62695138caSHui std::jthread jt; 63695138caSHui try { 64695138caSHui jt.detach(); 65695138caSHui assert(false); 66695138caSHui } catch (const std::system_error& err) { 67695138caSHui assert(err.code() == std::errc::invalid_argument); 68695138caSHui } 69695138caSHui } 70695138caSHui #endif 71695138caSHui 72695138caSHui std::this_thread::sleep_for(std::chrono::milliseconds{2}); 73695138caSHui return 0; 74695138caSHui } 75