std::inplace_stop_source::request_stop
From cppreference.com
bool request_stop() noexcept;
|
(since C++26) | |
Issues a stop request to the inplace stop-state, if the inplace_stop_source object has not yet already had stop requested, as described on stoppable-source page.
Postconditions
stop_requested() is true.
Return value
true if this invocation made a stop request, otherwise false.
Example
Run this code
#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>
using namespace std::literals::chrono_literals;
// Fallback to non-inplace stop-* components
#if __cpp_lib_senders < 202406L
#define inplace_stop_source stop_source
#define inplace_stop_token stop_token
#define inplace_stop_callback stop_callback
#endif
int main()
{
// Create a stop source with embedded stop-state.
std::inplace_stop_source source;
// Obtain an associated token to distribute it to workers.
std::inplace_stop_token token = source.get_token();
// Register a callback that runs automatically when a stop is requested.
// The lifetime of the callback must not exceed the lifetime of source!
std::inplace_stop_callback stop_callback(token, []() noexcept
{
std::cout << "[Callback] Cleaning up resources..." << std::endl;
});
// Start a polling worker thread
std::thread worker([token]() mutable
{
std::cout << "[Worker] Thread started. Polling for work..." << std::endl;
while (!token.stop_requested())
{
std::cout << "[Worker] Doing hard work..." << std::endl;
std::this_thread::sleep_for(300ms);
}
std::cout << "[Worker] Thread gracefully exiting." << std::endl;
});
// Let the worker run for a brief moment
std::this_thread::sleep_for(1000ms);
// Trigger cancellation. This flips the internal stop-state, synchronously
// executes the registered callback, and unblocks the worker loop.
std::cout << "[Main] Triggering stop request..." << std::endl;
source.request_stop();
worker.join();
std::cout << "[Main] Worker thread joined. Program finished." << std::endl;
}
Possible output:
[Worker] Thread started. Polling for work...
[Worker] Doing hard work...
[Worker] Doing hard work...
[Worker] Doing hard work...
[Worker] Doing hard work...
[Main] Triggering stop request...
[Callback] Cleaning up resources...
[Worker] Thread gracefully exiting.
[Main] Worker thread joined. Program finished.
See also
| makes a stop request for the associated stop-state, if any (public member function of std::stop_source)
|