#include<thread>
#include<iostream>// Simple functionvoidtask(){std::cout<<"Hello from jthread!\n";}// Function that accepts stop_tokenvoidcancellable_task(std::stop_tokenstoken){inti=0;while(!stoken.stop_requested()){std::cout<<i++<<" ";std::this_thread::sleep_for(std::chrono::milliseconds(10));}}intmain(){// Basic usage - auto-joinsstd::jthreadt1(task);// With stop tokenstd::jthreadt2(cancellable_task);std::this_thread::sleep_for(std::chrono::milliseconds(350));t2.request_stop();// Request cancellation. non blockingstd::cout<<"terminated"<<std::endl;std::this_thread::sleep_for(std::chrono::milliseconds(100));// Both threads automatically joined when they go out of scope. // If no request_stop is issued, the thread will be called with std::stop_token automatically. // Thread destruction at the end will be blocking }
In a more advanced case, one can control when to stop multiple threads using std::stop_source, from an arbitrary thread:
#include<thread>
#include<iostream>
#include<chrono>voidworker(std::stop_tokenstoken,intid){while(!stoken.stop_requested()){std::cout<<"Worker "<<id<<" running\n";std::this_thread::sleep_for(std::chrono::milliseconds(200));}std::cout<<"Worker "<<id<<" stopped\n";}intmain(){// Create a stop_source manuallystd::stop_sourcesource;// Create multiple threads that share the same stop mechanismstd::jthreadt1(worker,source.get_token(),1);std::jthreadt2(worker,source.get_token(),2);std::jthreadt3(worker,source.get_token(),3);std::this_thread::sleep_for(std::chrono::seconds(1));// Stop all threads at once using the shared sourcestd::cout<<"Requesting stop for all workers\n";source.request_stop();// All threads will stop and auto-join when they go out of scope}
1
- `std::stop_token` must be used with `std::stop_source`, but `std::stop_source` could be passed around as reference or value.