CKTIS / C++
std::stop_token::stop_requested — check for a stop request
Check whether a shared stop state has received a request so work can stop at a safe point. A `true` result does not mean the thread has finished.
Version: ISO C++23; implementation support may vary
Syntax
bool stop_requested() const noexcept;std::stop_token::stop_requested is a member function from <stop_token>, introduced in C++20 and available in C++23. Call token.stop_requested() with no arguments. The member is const noexcept and returns true only if the associated stop state has received a stop request. Otherwise it returns false, including for a default-constructed token, which has no stop state.
std::stop_source::get_token() returns a token that shares the source's stop state rather than a snapshot of its flag. The token keeps that state alive, so destroying the source does not clear a recorded request. token.stop_possible() answers a different question: it is true if a request has already been made or an associated source still exists that can make one.
std::stop_source::request_stop() issues the request and returns true only when it records the first request for that state. It returns false when the state was already requested to stop or the source has no state. A request cannot be withdrawn. std::jthread::request_stop() acts on the std::jthread object's internal source; a token from get_stop_token() observes that same state.
Cancellation is cooperative: check the token between units of work and exit at a safe point. A true result reports a request, not thread completion. The request alone does not interrupt an arbitrary blocking operation.
Examples
#include <iostream>
#include <stop_token>
int main() {
std::stop_token token;
std::cout << std::boolalpha;
{
std::stop_source source;
token = source.get_token();
std::cout << "Before request: " << token.stop_requested() << '\n';
std::cout << "First request: " << source.request_stop() << '\n';
std::cout << "Repeated request: " << source.request_stop() << '\n';
}
std::cout << "After source destruction: " << token.stop_requested() << '\n';
std::cout << "Empty token: " << std::stop_token{}.stop_requested() << '\n';
}
Result
Before request: false First request: true Repeated request: false After source destruction: true Empty token: false
The program launches no threads. The first request is recorded and the second changes nothing. The token still sees the request after the source is destroyed; the empty token returns `false`.
Related lessons
- C++ · Lesson 39 · Advanced · Version: 3
- C++ · Lesson 44 · Advanced · Version: 3