Skip to content

Commit 1649cf3

Browse files
committed
fix(when_any): guard stop callback against inline completion destroying the opstate
If every child completes set_stopped() synchronously from inside __stop_source_.request_stop() (senders that complete inline from their stop callbacks), __count_ reaches zero and the receiver is completed -- destroying the operation state, including __stop_source_, while request_stop() is still iterating its callback list. The subsequent relock then spins on freed memory. Adopt __when_all's rug-pull guard: temporarily increment __count_ around request_stop() in the stop callback and arrive afterwards, so completion is deferred until the callback has returned.
1 parent 61fb73d commit 1649cf3

1 file changed

Lines changed: 24 additions & 2 deletions

File tree

‎include/exec/when_any.hpp‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,25 @@ namespace experimental::execution
8383

8484
STDEXEC_IMMOVABLE(__opstate_base);
8585

86+
struct __forward_stop_request
87+
{
88+
constexpr void operator()() const noexcept
89+
{
90+
// Temporarily increment the count to avoid concurrent/recursive arrivals to
91+
// pull the rug under our feet. Relaxed memory order is fine here.
92+
__op_->__count_.fetch_add(1, __std::memory_order_relaxed);
93+
94+
__op_->__stop_source_.request_stop();
95+
96+
// Arrive in order to decrement the count again and complete if needed.
97+
__op_->__arrive();
98+
}
99+
100+
__opstate_base* __op_;
101+
};
102+
86103
using __on_stop =
87-
stop_callback_for_t<stop_token_of_t<env_of_t<_Receiver>&>, __forward_stop_request<>>;
104+
stop_callback_for_t<stop_token_of_t<env_of_t<_Receiver>&>, __forward_stop_request>;
88105

89106
inplace_stop_source __stop_source_{};
90107
std::optional<__on_stop> __on_stop_{};
@@ -127,6 +144,11 @@ namespace experimental::execution
127144
// stop pending operations
128145
__stop_source_.request_stop();
129146
}
147+
__arrive();
148+
}
149+
150+
constexpr void __arrive() noexcept
151+
{
130152
// make __result_ emplacement visible when __count_ goes from one to zero
131153
// This relies on the fact that each sender will call notify() at most once
132154
if (__count_.fetch_sub(1, __std::memory_order_acq_rel) == 1)
@@ -203,7 +225,7 @@ namespace experimental::execution
203225
void start() & noexcept
204226
{
205227
this->__on_stop_.emplace(get_stop_token(get_env(this->__rcvr_)),
206-
__forward_stop_request{this->__stop_source_});
228+
typename __op_base_t::__forward_stop_request{this});
207229
if (this->__stop_source_.stop_requested())
208230
{
209231
STDEXEC::set_stopped(static_cast<_Receiver&&>(this->__rcvr_));

0 commit comments

Comments
 (0)