Add PR check to suggest alternatives to using undef (#118506)
[llvm-project.git] / libcxx / test / std / thread / thread.jthread / dtor.pass.cpp
blob0dde648584cac0dadf59f34a28995739ab4a31c4
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
13 // ~jthread();
15 #include <atomic>
16 #include <cassert>
17 #include <optional>
18 #include <stop_token>
19 #include <thread>
20 #include <type_traits>
21 #include <vector>
23 #include "make_test_thread.h"
24 #include "test_macros.h"
26 int main(int, char**) {
27 // !joinable()
29 std::jthread jt;
30 assert(!jt.joinable());
33 // If joinable() is true, calls request_stop() and then join().
34 // request_stop is called
36 std::optional<std::jthread> jt = support::make_test_jthread([] {});
37 bool called = false;
38 std::stop_callback cb(jt->get_stop_token(), [&called] { called = true; });
39 jt.reset();
40 assert(called);
43 // If joinable() is true, calls request_stop() and then join().
44 // join is called
46 std::atomic_int calledTimes = 0;
47 std::vector<std::jthread> jts;
49 constexpr auto numberOfThreads = 10u;
50 jts.reserve(numberOfThreads);
51 for (auto i = 0u; i < numberOfThreads; ++i) {
52 jts.emplace_back(support::make_test_jthread([&calledTimes] {
53 std::this_thread::sleep_for(std::chrono::milliseconds{2});
54 calledTimes.fetch_add(1, std::memory_order_relaxed);
55 }));
57 jts.clear();
59 // If join was called as expected, calledTimes must equal to numberOfThreads
60 // If join was not called, there is a chance that the check below happened
61 // before test threads incrementing the counter, thus calledTimed would
62 // be less than numberOfThreads.
63 // This is not going to catch issues 100%. Creating more threads would increase
64 // the probability of catching the issue
65 assert(calledTimes.load(std::memory_order_relaxed) == numberOfThreads);
68 return 0;