Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::stop_token — cooperative operation cancellation

std::stop_token lets an operation check whether a stop request has been made. Its stop_requested() member reads shared state; the token itself neither stops a thread nor issues a request.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <stop_token>
std::stop_source source;
std::stop_token token = source.get_token();
bool requested = token.stop_requested();
// Member signature: bool stop_requested() const noexcept;

std::stop_token, declared in <stop_token>, supports cooperative stopping of operations. A std::stop_source supplies a token through get_token() and issues a request through request_stop(). Token copies share ownership of the stop state, if any. The operation's code must respond to the request itself; this is not forced thread interruption.

std::stop_token::stop_requested() has the signature bool stop_requested() const noexcept;. It returns true when the associated state has received a stop request, and false otherwise. A request cannot be withdrawn. Reading false does not guarantee that a request will not arrive immediately afterward.

stop_possible() answers a different question: it returns false when the token has no state, or when no request has been made and no associated std::stop_source remains. Otherwise it returns true, including after a request. Both methods return false for a default-constructed token.

The example deliberately creates no threads, making its output deterministic. It shows an empty token and an associated token before and after a request. This entry targets C++23; the supplied working draft is a living document, not a frozen C++23 edition.

Examples

#include <iostream>
#include <stop_token>

int main() {
    std::stop_source source;
    std::stop_token token = source.get_token();
    std::stop_token empty;

    std::cout << std::boolalpha;
    std::cout << empty.stop_possible() << ' '
              << empty.stop_requested() << '\n';
    std::cout << token.stop_possible() << ' '
              << token.stop_requested() << '\n';
    source.request_stop();
    std::cout << token.stop_possible() << ' '
              << token.stop_requested() << '\n';
}

Result

false false
true false
true true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources