Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::stop_source — a source of stop requests

std::stop_source provides shared stop-request state. get_token() exposes that state for observation, while request_stop() requests stopping. This is a cooperative mechanism: it does not automatically interrupt a running thread.

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 first_request = source.request_stop();

// Member signatures:
// std::stop_token get_token() const noexcept;
// bool request_stop() noexcept;

std::stop_source, declared in <stop_token>, supports cooperative stopping. Default construction creates a new state with no stop requested; copies of the source share that state. Working code must check a token or use a mechanism that responds to a stop request. The source itself neither starts nor terminates a thread.

std::stop_source::get_token() has the signature std::stop_token get_token() const noexcept. It returns a token associated with the source's state; the token can observe requests through stop_requested(), but cannot request stopping. A source constructed as std::stop_source{std::nostopstate} has no state: get_token() then returns an empty token, and request_stop() returns false.

std::stop_source::request_stop() has the signature bool request_stop() noexcept. It atomically makes the first request for the shared state and returns true only to the call that made it. Later calls return false; this means neither failure nor confirmation that work has finished. A request cannot be undone: a new cycle needs a new state.

Registered callbacks execute synchronously when the first request is made, so request_stop() can execute user code before returning. An exception escaping such a callback causes std::terminate. The example deliberately creates no threads: it deterministically shows the state change observed through the token.

Examples

#include <iostream>
#include <stop_token>

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

    std::cout << std::boolalpha;
    std::cout << "before: " << token.stop_requested() << '\n';

    const bool first = source.request_stop();
    const bool second = source.request_stop();

    std::cout << "requests: " << first << ' ' << second << '\n';
    std::cout << "after: " << token.stop_requested() << '\n';
}

Result

before: false
requests: true false
after: 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