15#if defined(__cpp_lib_jthread) && __cpp_lib_jthread >= 201911L
22 using std::stop_source;
23 using std::stop_token;
30# include <type_traits>
41 explicit stop_token(std::shared_ptr<std::atomic<bool>> flag) noexcept
42 : flag_(std::move(flag))
48 return flag_ && flag_->load(std::memory_order_acquire);
53 return static_cast<bool>(flag_);
57 std::shared_ptr<std::atomic<bool>> flag_;
64 stop_source() : flag_(std::make_shared<std::atomic<bool>>(false)) {}
73 if (!flag_)
return false;
74 bool expected =
false;
75 return flag_->compare_exchange_strong(
76 expected,
true, std::memory_order_release, std::memory_order_acquire);
81 return flag_ && flag_->load(std::memory_order_acquire);
85 std::shared_ptr<std::atomic<bool>> flag_;
95 template <typename F, typename... Args>
98 if constexpr (std::is_invocable_v<F&,
stop_token, Args&...>)
100 thread_ = std::thread(
101 [fn = std::forward<F>(f), tok = source_.get_token()](
102 auto&&... a)
mutable {
103 fn(tok, std::forward<decltype(a)>(a)...);
105 std::forward<Args>(args)...);
109 thread_ = std::thread(std::forward<F>(f), std::forward<Args>(args)...);
115 if (thread_.joinable())
117 source_.request_stop();
126 : source_(std::move(other.source_)), thread_(std::move(other.thread_))
134 if (thread_.joinable())
136 source_.request_stop();
139 source_ = std::move(other.source_);
140 thread_ = std::move(other.thread_);
145 [[nodiscard]]
bool joinable() const noexcept {
return thread_.joinable(); }
146 void join() { thread_.join(); }
152 return source_.get_token();
158 std::thread thread_{};
jthread() noexcept=default
stop_source get_stop_source() const noexcept
stop_token get_stop_token() const noexcept
jthread & operator=(jthread &&other) noexcept
jthread(const jthread &)=delete
bool request_stop() noexcept
jthread & operator=(const jthread &)=delete
jthread(jthread &&other) noexcept
bool joinable() const noexcept
Owner side of the stop signal. Setting it is sticky and atomic.
stop_token get_token() const noexcept
bool stop_requested() const noexcept
bool request_stop() noexcept
bool stop_requested() const noexcept
stop_token(std::shared_ptr< std::atomic< bool > > flag) noexcept
bool stop_possible() const noexcept
compat::stop_source stop_source
compat::stop_token stop_token