Threads Stop_token library C++














































Threads Stop_token library C++



Introduction

First let us go through the definiton of few terms before understanding stop_token class::

  • std::jthread - C++ class for a joining and cooperative interruptible thread with stop_token helper.
  • std::stop_source - provides the means to issue a stop request, such as for std::jthread cancellation. A stop request made for one stop_source object is visible to all stop_sources.
Now,
  1. The stop_token class provides the means to check if a stop request has been made or can be made, for its associated std::stop_source object.
  2.  It is essentially a thread-safe "view" of the associated stop-state.
  3. A stop_token object is not generally constructed independently, but rather retrieved from a std::jthread or std::stop_source. This makes it share the same associated stop-state as the std::jthread or std::stop_source.

The stop_token can also be passed to the constructor of std::stop_callback, such that the callback will be invoked if the stop_token's associated std::stop_source is requested to stop.

 And stop_token can be passed to the interruptible waiting functions of std::condition_variable_any, to interrupt the condition variable's wait if stop is requested.

  •  request_stop() returns whether the stop state was changed.
  •  stop_callback has type member callback_type. 
  •  stop_callback constructor supports copying/conversion of callback.
  •  stop_callback deduction guide now deduces to decayed type.
Few Member Functions are:

  • constructor()-constructs new stop_token object
  • destructor()-destructs stop_token object
  • operator= -assigns the stop_token object
Modifiers:

  • swap() - swaps two stop_token object
Observers

  •   stop_requested - checks whether the associated stop-state has been requested to stop
  •    stop_possible   - checks whether associated stop-state can be requested to stop
Non-member functions

  • operator== -  compares two std::stop_token objects
An Example Code:

#include<thread>

void func1(std::stop_token st)  // initializing stop token
{
std::cout<<"start"<<'\n';
while(!st.stop_requested())
{  std::cout<<"working"<<'\n';
}
std::cout<<"stop"<<'\n';
}
int main()
  std::jthread t{func1};
  for(int i=0;i<100;i++)
       std::this_thread::yield();  
   //using the for loop to execute for some time,if not used stop would be immediately called after start.
}
Output

start
working
working 
working
.
.
.
.
.
.
stop.



Comments