1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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
21 #include <system_error>
23 #include <type_traits>
26 #include "make_test_thread.h"
27 #include "test_macros.h"
29 int main(int, char**) {
30 // Effects: Blocks until the thread represented by *this has completed.
32 std::atomic_int calledTimes
= 0;
33 std::vector
<std::jthread
> jts
;
34 constexpr auto numberOfThreads
= 10u;
35 jts
.reserve(numberOfThreads
);
36 for (auto i
= 0u; i
< numberOfThreads
; ++i
) {
37 jts
.emplace_back(support::make_test_jthread([&] {
38 std::this_thread::sleep_for(std::chrono::milliseconds(2));
39 calledTimes
.fetch_add(1, std::memory_order_relaxed
);
43 for (auto i
= 0u; i
< numberOfThreads
; ++i
) {
47 // If join did block, calledTimes must equal to numberOfThreads
48 // If join did not block, there is a chance that the check below happened
49 // before test threads incrementing the counter, thus calledTimed would
50 // be less than numberOfThreads.
51 // This is not going to catch issues 100%. Creating more threads to increase
52 // the probability of catching the issue
53 assert(calledTimes
.load(std::memory_order_relaxed
) == numberOfThreads
);
56 // Synchronization: The completion of the thread represented by *this synchronizes with
57 // ([intro.multithread]) the corresponding successful join() return.
60 std::jthread jt
= support::make_test_jthread([&] { flag
= true; });
62 assert(flag
); // non atomic write is visible to the current thread
65 // Postconditions: The thread represented by *this has completed. get_id() == id().
67 std::jthread jt
= support::make_test_jthread([] {});
68 assert(jt
.get_id() != std::jthread::id());
70 assert(jt
.get_id() == std::jthread::id());
73 #if !defined(TEST_HAS_NO_EXCEPTIONS)
74 // Throws: system_error when an exception is required ([thread.req.exception]).
75 // invalid_argument - if the thread is not joinable.
81 } catch (const std::system_error
& err
) {
82 assert(err
.code() == std::errc::invalid_argument
);