Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A coroutine doesn't do anything more than a callback does -- it's just syntactic sugar.

The default behaviour of many asynchronous systems is to extend the lifetime of context data until all the asynchronous handlers have run. You can also just bind them to the resource instead which is arguably more elegant, but which depends on how cancellation is implemented.



Any data that needs to survive across several callback invocations requires shared ownership. This means that the data must be allocated on the heap and probably also requires reference counting. With lambdas it's also easy to make mistakes, e.g. by capturing variables on the stack by reference.

In a coroutine everything can just live on the stack because the stack frame itself is kept alive across the asynchronous function calls.

Don't you see the big difference regarding lifetime management?


Not necessarily, I already explained how (resource binding).

Close the socket, all handlers are cancelled, context can be freed immediately. The socket owns the data.


> The socket owns the data.

What if there's more than one socket involved?


Then you have it owned by the parent which owns all relevant sockets.

Resource ownership management 101.


But that's not what you want. The context object should be freed when the associated operation finishes (either successfully or with an error), not when the parent goes out of scope. With coroutines I can simply put the context object on the stack and when the task finishes, the object automatically goes out of scope.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: