Debian Codegraph @

libcxx/test/std/thread/thread.stoptoken/stopsource/stop_requested.pass.cpp

raw
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
13
14 // [[nodiscard]] bool stop_requested() const noexcept;
15 // true if *this has ownership of a stop state that has received a stop request; otherwise, false.
16
17 #include <cassert>
18 #include <chrono>
19 #include <concepts>
20 #include <optional>
21 #include <stop_token>
22 #include <type_traits>
23
24 #include "make_test_thread.h"
25 #include "test_macros.h"
26
27 template <class T>
28 concept IsStopRequestedNoexcept = requires(const T& t) {
29 { t.stop_requested() } noexcept;
30 };
31
32 static_assert(IsStopRequestedNoexcept<std::stop_source>);
33
34 int main(int, char**) {
35 // no state
36 {
37 const std::stop_source ss{std::nostopstate};
38 assert(!ss.stop_requested());
39 }
40
41 // has state
42 {
43 std::stop_source ss;
44 assert(!ss.stop_requested());
45
46 ss.request_stop();
47 assert(ss.stop_requested());
48 }
49
50 // request from another instance with same state
51 {
52 std::stop_source ss1;
53 auto ss2 = ss1;
54 ss2.request_stop();
55 assert(ss1.stop_requested());
56 }
57
58 // request from another instance with different state
59 {
60 std::stop_source ss1;
61 std::stop_source ss2;
62
63 ss2.request_stop();
64 assert(!ss1.stop_requested());
65 }
66
67 // multiple threads
68 {
69 std::stop_source ss;
70
71 std::thread t = support::make_test_thread([&]() { ss.request_stop(); });
72
73 t.join();
74 assert(ss.stop_requested());
75 }
76
77 // [thread.stopsource.intro] A call to request_stop that returns true
78 // synchronizes with a call to stop_requested on an associated stop_source
79 // or stop_source object that returns true.
80 {
81 std::stop_source ss;
82
83 bool flag = false;
84
85 std::thread t = support::make_test_thread([&]() {
86 using namespace std::chrono_literals;
87 std::this_thread::sleep_for(1ms);
88
89 // happens-before request_stop
90 flag = true;
91 auto b = ss.request_stop();
92 assert(b);
93 });
94
95 while (!ss.stop_requested()) {
96 std::this_thread::yield();
97 }
98
99 // write should be visible to the current thread
100 assert(flag == true);
101
102 t.join();
103 }
104
105 return 0;
106 }