Open Spongman opened 1 year ago
@Spongman I'm quite certain that this behaviour is as expected with the following reasoning:
outer()
is part of a larger expression and therefore kept alive to the end of the entire expression.co_return
performs a "final suspend" on the coroutine, therefore the coroutine is put to sleep until the coroutine_handle
is destroyed. Therefore the stack inside the coroutine is kept alive.coroutine_handle
is destroyed when destructing the return type of outer()
and not when reaching co_return
, the message is printed at the end of the expression.Yeah, i figured it had something to do with the lifetime of the coroutine. i'm not familiar with the internal details, but it does seem to me like the frame should be deleted before the callback is invoked.
Here's another example that illustrates this independent of the way it's invoked:
cti::coroutine<> inner() | void inner()
{ | {
Foo local; | Foo local;
co_return; | return;
} | }
|
cti::coroutine<> outer() | void outer()
{ | {
co_await inner(); | inner();
cerr << "inner done\n"; | cerr << "inner done\n";
co_return; | return;
} | }
In the synchronous version on the right, obviously local
's destructor is called before "inner done" is printed.
However, in the async version on the left, local
's destructor isn't called until after "inner done" is printed.
Regardless of the internal implementation, that just doesn't seem right to me: it means the scope rules of RAII are essentially broken in coroutines.
Ok, I totally agree with you now.
I'm not sure if this is easy to fix, since in general it is not explicitly specified by the library design when the destruction of the outer continuation occurs after it was used. Therefore, the behavior you describe may also vary depending on whether you resolve the continuable/coroutine asynchronously or synchronously. For callable objects this behavior has never been an issue before, but for coroutine handles we should not keep the scope of the coroutine alive because this can lead to very unexpected results as you have said.
@Naios
I'm not sure if this is an issue with the continuable lib, or if I'm doing something wrong, or if I just funamentally don't understand how coroutines are supposed to work...
The issue is that the destructor for a local object in a coroutine is getting called after the
co_return
has 'returned' control to the caller:https://gcc.godbolt.org/z/cT7rv93hP
this outputs:
i would expect that last two lines to be swapped, as it would be if this were a normal synchronous function.
maybe I'm managing the lifetime of the future incorrectly? or that just the way it's supposed to work with coroutines?
Commit Hash
master
(plus my clang fix)