Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To initialize an std::stopcallback, you can use the constructor of the std::stoptoken class. Here is an example:

#include <iostream>
#include <stop_token>

void my_function(std::stop_token token) {
  while (!token.stop_requested()) {
    std::cout << "Running..." << std::endl;
  }
  std::cout << "Stopped." << std::endl;
}

int main() {
  std::jthread thread(my_function);
  std::this_thread::sleep_for(std::chrono::seconds(1));
  thread.request_stop();
}

In this example, we use the std::jthread class to create a new thread and pass it the function myfunction. This function takes an std::stoptoken parameter, which we use to check if the thread should stop. In the main function, we wait for 1 second and then call the request_stop method on the thread object to signal that the thread should stop.