| 1 | //===----------------------------------------------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // UNSUPPORTED: no-threads |
| 10 | // UNSUPPORTED: c++03, c++11, c++14, c++17 |
| 11 | // XFAIL: availability-synchronization_library-missing |
| 12 | |
| 13 | // void detach(); |
| 14 | |
| 15 | #include <atomic> |
| 16 | #include <cassert> |
| 17 | #include <chrono> |
| 18 | #include <concepts> |
| 19 | #include <functional> |
| 20 | #include <optional> |
| 21 | #include <system_error> |
| 22 | #include <thread> |
| 23 | #include <type_traits> |
| 24 | |
| 25 | #include "make_test_thread.h" |
| 26 | #include "test_macros.h" |
| 27 | |
| 28 | int main(int, char**) { |
| 29 | // Effects: The thread represented by *this continues execution without the calling thread blocking. |
| 30 | { |
| 31 | std::atomic_bool start{false}; |
| 32 | std::atomic_bool done{false}; |
| 33 | std::optional<std::jthread> jt = support::make_test_jthread([&start, &done] { |
| 34 | start.wait(false); |
| 35 | done = true; |
| 36 | }); |
| 37 | |
| 38 | // If it blocks, it will deadlock here |
| 39 | jt->detach(); |
| 40 | |
| 41 | jt.reset(); |
| 42 | |
| 43 | // The other thread continues execution |
| 44 | start = true; |
| 45 | start.notify_all(); |
| 46 | while (!done) { |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // Postconditions: get_id() == id(). |
| 51 | { |
| 52 | std::jthread jt = support::make_test_jthread([] {}); |
| 53 | assert(jt.get_id() != std::jthread::id()); |
| 54 | jt.detach(); |
| 55 | assert(jt.get_id() == std::jthread::id()); |
| 56 | } |
| 57 | |
| 58 | #if !defined(TEST_HAS_NO_EXCEPTIONS) |
| 59 | // Throws: system_error when an exception is required ([thread.req.exception]). |
| 60 | // invalid_argument - if the thread is not joinable. |
| 61 | { |
| 62 | std::jthread jt; |
| 63 | try { |
| 64 | jt.detach(); |
| 65 | assert(false); |
| 66 | } catch (const std::system_error& err) { |
| 67 | assert(err.code() == std::errc::invalid_argument); |
| 68 | } |
| 69 | } |
| 70 | #endif |
| 71 | |
| 72 | std::this_thread::sleep_for(rtime: std::chrono::milliseconds{2}); |
| 73 | return 0; |
| 74 | } |
| 75 | |