Skip to content

Keep the callable passed to create_task alive while the task runs - #59

Merged
otamachan merged 1 commit into
mainfrom
create-task-owns-callable
Oct 18, 2026
Merged

otamachan merged 1 commit into
mainfrom
create-task-owns-callable

Conversation

@otamachan

Copy link
Copy Markdown
Owner

create_task(callable) invoked a temporary lambda and returned its task, but the lambda was destroyed at the end of the caller's full-expression. A coroutine lambda reads its captures through the closure, so any capture used after the first suspension was dangling:

auto task = ctx.create_task([&ctx, &count]() -> Task<void> {
  co_await ctx.sleep(1s);
  count++;  // the closure holding &count is already gone
});

This is the pattern the guide and the examples use. Under ASan, TimerStreamTest.BasicNext reported stack-use-after-scope (mentioned in #56).

The callable is now moved into a wrapper coroutine's frame, which awaits the task it returns, so the captures live as long as the task.

SleepTest.CreateTaskKeepsTheLambdaAlive checks that the lambda's captures are still alive after create_task returns. It fails on main, where the capture has already been destroyed. With this change, the full suite passes in Debug, and test_sleep / test_timer_stream are clean under ASan.

create_task(callable) invoked a temporary lambda and returned its task,
but the lambda was destroyed at the end of the caller's full-expression.
A coroutine lambda reads its captures through the closure, so any
capture used after the first suspension was dangling. This is the
pattern the guide and examples use; under ASan
TimerStreamTest.BasicNext reported stack-use-after-scope.

Move the callable into a wrapper coroutine's frame, which awaits the
task it returns.
@otamachan
otamachan merged commit 1a12edd into main Oct 18, 2026
6 checks passed
@otamachan
otamachan deleted the create-task-owns-callable branch October 18, 2026 03:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant