std::inplace_stop_token
From cppreference.com
| Defined in header <stop_token>
|
||
class inplace_stop_token;
|
(since C++26) | |
Provides a lightweight, cooperative cancellation token tied to a non-shared or locally-scoped std::inplace_stop_source, avoiding the heap-allocated control blocks of std::stop_token when lifetimes are well-nested. The inplace_stop_token references the stop-state of its associated std::inplace_stop_source object, if any.
The inplace_stop_token models the concept stoppable_token.
Member alias templates
| Type | Definition |
callback_type<Callback> (since C++26)
|
std::inplace_stop_callback<Callback>
|
Data members
| Member | Description |
const std::inplace_stop_source* stop_source_ (private)
|
a pointer to an associated object (exposition-only member object*) |
Member functions
constructs new inplace_stop_token object (public member function) | |
(destructor) (implicitly declared) |
destructs the inplace_stop_token object (public member function) |
compares two inplace_stop_token objects (public member function) | |
Modifiers | |
swaps two inplace_stop_token objects (public member function) | |
Observers | |
| checks whether the associated stop-state has been requested to stop (public member function) | |
| checks whether associated stop-state can be requested to stop (public member function) | |
Notes
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_senders |
202406L |
(C++26) | std::inplace_stop_token
|
Example
Run this code
#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>
using namespace std::chrono_literals;
void perform_heavy_computation(std::inplace_stop_token stop_token)
{
while (!stop_token.stop_requested())
{
std::cout << "Working...\n" << std::flush;
std::this_thread::sleep_for(100ms);
}
std::cout << "Stopping due to cancellation!\n" << std::flush;
}
int main()
{
std::inplace_stop_source stop_source;
// Retrieve the token and pass it to a worker thread
std::jthread worker(perform_heavy_computation, stop_source.get_token());
std::this_thread::sleep_for(350ms);
std::cout << "Requesting stop...\n" << std::flush;
stop_source.request_stop();
} // worker thread joins automatically here
Possible output:
Working...
Working...
Working...
Working...
Requesting stop...
Stopping due to cancellation!
See also
(C++20) |
an interface for querying if a std::jthread cancellation request has been made (class) |
(C++26) |
a stoppable source that is the sole owner of its stop-state (class) |
External links
| 1. | NVIDIA: stdexec::inplace_stop_token — github.com
|
| 2. | Beman-project: execution::inplace_stop_token — github.com
|