4 ms·
With callbacks you have to make sure that your data persists across the function calls. This necessarily requires more heap allocations (or copies) than in a co
by spacechild1 7mo ago
With callbacks you have to make sure that your data persists across the function calls. This necessarily requires more heap allocations (or copies) than in a coroutine where most data can just live on the stack.
- mgaunard 7mo agoA 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.
- spacechild1 7mo agoAny 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?
- mgaunard 7mo agoNot necessarily, I already explained how (resource binding). Close the socket, all handlers are cancelled, context can be freed immediately. The socket owns the data.
- spacechild1 7mo ago> The socket owns the data. What if there's more than one socket involved?
- mgaunard 7mo agoThen you have it owned by the parent which owns all relevant sockets. Resource ownership management 101.
- spacechild1 7mo agoBut 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.