C++ Library - <stop_token>
The <stop_token> header in C++20, introduces a mechanism for cancellation of threads and asynchronous operations. It works in conjunction with the std::stop_source, which is responsible for generating stop requests.
These are used to implement a responsive systems that can halt operations without the need for forceful termination or complicated signaling mechanism.
Including <stop_token> Header
To include the <stop_token> header in your C++ program, you can use the following syntax.
#include <stop_token>
Functions of <stop_token> Header
Below is list of all functions from <stop_token> header.
| Sr.No | Functions & Description |
|---|---|
| 1 | operator=
It assigns the stop_token object. |
| 2 | swap
It swaps two stop_token objects. |
| 3 | stop_requested
It checks whether the associated stop-state has been requested to stop. |
| 4 | stop_possible
It checks whether associated stop-state can be requested to stop. |
| 5 | get_token
It returns a stop_token for the associated stop-state. |
Using Multiple Threads with Stop Tokens
In the following example, we are going to use the std::stop_source to control the multiple threads.
#include <iostream>
#include <thread>
#include <stop_token>
#include <chrono>
void a(int id, std::stop_token b) {
while (!b.stop_requested()) {
std::cout << "A " << id << " Is Working.." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(600));
}
std::cout << "A " << id << " Is Cancelled.." << std::endl;
}
int main() {
std::stop_source x;
std::thread x1(a, 1, x.get_token());
std::thread x2(a, 2, x.get_token());
std::this_thread::sleep_for(std::chrono::seconds(2));
x.request_stop();
x1.join();
x2.join();
return 0;
}
Output
Output of the above code is as follows −
A 2 Is Working.. A 1 Is Working.. A 2 Is Working.. A 1 Is Working.. A 2 Is Working.. A 1 Is Working.. A 2 Is Working.. A 1 Is Working.. A 2 Is Cancelled.. A 1 Is Cancelled..