Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libcxx / test / std / thread / thread.jthread / detach.pass.cpp
blob54fd5fd93bed6f34f5ae32bae7662b610fd60b29
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: libcpp-has-no-experimental-stop_token
11 // UNSUPPORTED: c++03, c++11, c++14, c++17
12 // XFAIL: availability-synchronization_library-missing
14 // void detach();
16 #include <atomic>
17 #include <cassert>
18 #include <chrono>
19 #include <concepts>
20 #include <functional>
21 #include <optional>
22 #include <system_error>
23 #include <thread>
24 #include <type_traits>
26 #include "make_test_thread.h"
27 #include "test_macros.h"
29 int main(int, char**) {
30 // Effects: The thread represented by *this continues execution without the calling thread blocking.
32 std::atomic_bool start{false};
33 std::atomic_bool done{false};
34 std::optional<std::jthread> jt = support::make_test_jthread([&start, &done] {
35 start.wait(false);
36 done = true;
37 });
39 // If it blocks, it will deadlock here
40 jt->detach();
42 jt.reset();
44 // The other thread continues execution
45 start = true;
46 start.notify_all();
47 while (!done) {
51 // Postconditions: get_id() == id().
53 std::jthread jt = support::make_test_jthread([] {});
54 assert(jt.get_id() != std::jthread::id());
55 jt.detach();
56 assert(jt.get_id() == std::jthread::id());
59 #if !defined(TEST_HAS_NO_EXCEPTIONS)
60 // Throws: system_error when an exception is required ([thread.req.exception]).
61 // invalid_argument - if the thread is not joinable.
63 std::jthread jt;
64 try {
65 jt.detach();
66 assert(false);
67 } catch (const std::system_error& err) {
68 assert(err.code() == std::errc::invalid_argument);
71 #endif
73 std::this_thread::sleep_for(std::chrono::milliseconds{2});
74 return 0;