Stop Token Header In C++20 - C++ Programming Tutorial
C++ Course / Miscellaneous / Stop Token Header In C++20

Stop Token Header In C++20

BLUF: Mastering Stop Token Header In C++20 is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Stop Token Header In C++20

C++ is renowned for its efficiency. Learn how Stop Token Header In C++20 enables low-level control and high-performance computing in the tutorial below.

This particular <stop_token> header was added to C++20 to offer effective tools for terminating asynchronous operations. It presents alternative and clearer methods for implementing cancellation through exceptions. It is a component of the thread support library.

What is a header?

A Header serves as a detailed set of guidelines outlining the arrangement and capabilities of a specific module or data. It includes statements for variables, functions, classes, and more. Headers are crucial for averting errors caused by inadequate definitions.

What are asynchronous operations?

Asynchronous operations enable a computer program to execute tasks independently without pausing for each task to complete before proceeding to the next one. This approach is valuable for managing numerous tasks concurrently. For instance, when sending a message to a friend, rather than halting all activities until a response is received, you can engage in other phone activities such as gaming or browsing. Meanwhile, the message is sent and awaits a reply in the background.

Classes present in the stop_token header:

It includes two main categories: the stopsource and the stoptoken class.

  • "stop_source":

This particular class embodies the origin of a cancellation request. It offers functionalities to initiate a cancellation and verify if one has been requested.

The element "

  • " is utilized for this purpose.

This class embodies a "view" into a stop_source, enabling the verification of a cancellation request and determining the necessity for issuing a cancellation.

What is "stop_source"?

It is employed to generate a mechanism for halting operations. It operates alongside stop_token. It is utilized to control the lifespan of an asynchronous task.

Syntax of the stop_source class:

It has the following syntax:

Example

#include <stop_token>
using namespace std;
stop_source myStopSource; 
stop_token myStopToken = myStopSource.get_token();

An instance of the stopsource class is instantiated and assigned the identifier myStopSource. The gettoken method produces a stop_token called mystopToken. This token is employed to monitor and halt requests.

Example:

Let's consider a sample program to demonstrate the stop_source class in C++.

Example

#include <iostream>
#include <thread>
#include <stop_token>
using namespace std;
void moveToyCar(std::stop_token st) {
 while (!st.stop_requested()) {
 cout << "Toy car is moving forward..." << std::endl;
 this_thread::sleep_for(chrono::seconds(1));
 }
 cout << "Toy car stopped." << std::endl;
}
int main() {
 stop_source myStopSource;
 jthread toyCarThread(moveToyCar, myStopSource.get_token());
 this_thread::sleep_for(chrono::seconds(5));
 myStopSource.request_stop();
 toyCarThread.join();
 return 0;
}

Output:

Explanation:

In this software, our objective is to manage the miniature automobile by advancing it and then halting its movement after a specific duration. We have the capability to halt the miniature vehicles at our discretion. The moveToyCar function is responsible for simulating the movement of the toy car. We instantiate an instance of stopsource named myStopSource to act as a control mechanism for cessation signals. Subsequently, we produce a corresponding cessation signal, "st", by utilizing myStopSource.gettoken. Following this, a jthread titled toyCarThread is initialized, and it triggers the moveToyCar function with the cessation signal after allowing the toy car to travel for 5 seconds. To prompt the toy car to stop, we invoke myStopSource.request_stop. The software then pauses for the toy car thread to complete its operation by utilizing toyCarThread.join.

What is "stop_token"?

The stop_token class is commonly employed with jthread or other asynchronous tasks to facilitate the identification of cancellation requests.

Syntax for the stop_token class:

It has the following syntax:

Example

#include <stop_token>
void asyncOperation(std::stop_token stoken) {
 while (!stoken.stop_requested()) {
 // Perform some work
 }
 // Cleanup or handle the cancellation
}
int main() {
 std::jthread myThread(asyncOperation);
 // Other main thread operations
 // Request stop for the thread
 myThread.request_stop();
 myThread.join();

This syntax will encompass the entities, variables, and functions:

Objects:

The instance myThread belonging to the class jthread symbolizes the thread of execution.

An object named Stoken of type stop_token signifies the stopping tokens.

Functions:

  • The asyncOperation function represents the asynchronous operation performed in the separate thread.
  • The request_stop function is used to request the stop thread.
  • The join function is used to wait for the associated thread.
  • Example:

Let's consider a program to demonstrate the stop_token class in C++:

Example

#include <iostream>
#include <thread>
#include <stop_token>
using namespace std; 
void nightLamp(stop_token stoken) {
 while (!stoken.stop_requested()) {
 cout << "Night lamp is ON." << endl;
 this_thread::sleep_for(chrono::seconds(1));
 }
 cout << "Night lamp turned OFF." << endl;
}
int main() {
 jthread lampThread(nightLamp);
 this_thread::sleep_for(chrono::seconds(5));
 lampThread.request_stop();
 lampThread.join();
 return 0;
}

Output:

Explanation:

This software simulates a night light that remains illuminated until manually switched off. The "nightlamp" function initiates a distinct thread named "jthread" and monitors the stop token to determine when it should be deactivated. Meanwhile, the primary thread pauses for a duration of 5 seconds before signaling the night light to power down through the utilization of request_stop on the jthread.

Conclusion:

In summary, the <stoptoken> header within C++20 brings in effective methods for terminating asynchronous operations, offering simpler ways for termination. This header encompasses vital components like stopsource and stop_token. These components enable collaborative termination, enabling software to react to termination requests, thereby strengthening the resilience and management of asynchronous processes.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience