C++23 Deducing this:
A standard C++20 IILE (Immediately Invoked Lambda Expression) coroutine [=](){...}() captures the temporary closure by reference, causing an immediate dangling reference once the statement evaluates. Using the explicit object parameter (this auto) forces the closure and its captures to be passed by value into the coroutine frame, binding their lifetime to the coroutine state.
operator->* Overload:
Replaces the easily missed trailing (); of an IILE. The operator evaluates left-to-right, perfectly forwarding and immediately invoking the callable. This shifts the execution trigger to the head of the block for immediate visual parsing.
ASYNC Macro:
Fuses the invocation trick and deducing this into a zero-overhead DSL. It enforces explicit captures (__VA_ARGS__) and strictly defines the promise return type (Coro), completely hiding the C++23 boilerplate.
Execution Flow:
pool_task always suspends initially. The thread pool queue stores this initial handle. The queue must never automatically repush the handle after resumption; continuation is strictly deferred to the awaited operation's await_suspend logic to prevent catastrophic spin-loops.
class thread_pool {
queue<std::coroutine_handle<>> work;
// ...
};
void thread_pool::submit(auto awaitable) {
// Used after free bug due to capture in anonymous type instance.
auto task = [=]() -> pool_task {
// always suspends initially
co_await awaitable;
// destroys itself in final suspend
}();
work.push(task.handle());
}
void thread_pool::submit(auto awaitable) {
auto task = lambda_invoker() ->* [=](this auto) -> pool_task {
co_await awaitable;
};
work.push(task.handle());
}
struct lambda_invoker {
auto operator->*(auto&& fn) {
return std::forward<decltype(fn)>(fn)();
}
};void thread_pool::submit(auto awaitable) {
auto task = ASYNC(pool_task, awaitable) {
co_await awaitable;
};
work.push(task.handle());
}
struct lambda_invoker {
auto operator->*(auto&& fn) {
return std::forward<decltype(fn)>(fn)();
}
};
#define ASYNC(Coro, ...) \
lambda_invoker() ->* [__VA_ARGS__](this auto) -> Coro
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.