Ask Your Question
2

What is the method for initializing std::stop_callback?

asked 2023-07-09 10:13:41 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-09 10:31:02 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-09 10:13:41 +0000

Seen: 10 times

Last updated: Jul 09 '23