std::jthrea..._stop_source(3)
Manual-page check β
: this is std::jthrea..._stop_source(3) from the C++ Standard Libary manual β yes, thatβs the spelling up top, donβt come for me π β and the main-character function is std::jthread::get_stop_source. C++20 girlies, this oneβs for you β¨
π NAME π
std::jthread::get_stop_source - std::jthread::get_stop_source β thatβs the whole name, and honestly itβs giving βI said what I saidβ π
β¨ Synopsis β¨
std::stop_source get_stop_source() noexcept; (since C++20)
okay so this returns a std::stop_source associated with the same shared stop-state as held internally by the jthread object. Like, the jthread has its little stop-state situation, and this hands you a source thatβs tied to that exact same shared stop-state. no cap π«Ά
πΈ Parameters πΈ
(none) β literally zero parameters, bestie. not a one. the void. π
π Return value π
A value of type std::stop_source associated with the stop-state held internally by the jthread object. thatβs the return value, and it ate β¨
π» Example π»
// Run this code
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string_view>
#include <thread>
using namespace std::chrono_literals;
int main()
{
std::cout << std::boolalpha;
auto print = [](std::string_view name, const std::stop_source&
source)
{
std::cout << name << ": stop_possible = " <<
source.stop_possible();
std::cout << ", stop_requested = " << source.stop_requested()
<< '\n';
};
// A worker thread
auto worker = std::jthread([](std::stop_token stoken)
{
for (int i = 10; i; --i)
{
std::this_thread::sleep_for(300ms);
if (stoken.stop_requested())
{
std::cout << " Sleepy worker is requested to stop\n";
return;
}
std::cout << " Sleepy worker goes back to sleep\n";
}
});
std::stop_source stop_source = worker.get_stop_source();
print("stop_source", stop_source);
std::cout << "\nPass source to other thread:\n";
auto stopper = std::thread(
[](std::stop_source source)
{
std::this_thread::sleep_for(500ms);
std::cout << "Request stop for worker via source\n";
source.request_stop();
},
stop_source);
stopper.join();
std::this_thread::sleep_for(200ms);
std::cout << '\n';
print("stop_source", stop_source);
}
π Possible output π
stop_source: stop_possible = true, stop_requested = false
Pass source to other thread:
Sleepy worker goes back to sleep
Request stop for worker via source
Sleepy worker is requested to stop
stop_source: stop_possible = true, stop_requested = true
okay bye bestie π«Ά β footer vibes: source http://cppreference.com, date 2024.06.10, page std::jthrea..._stop_source(3). mwah π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms