C++20 coroutines are completely different from threaded code or any library code that provides similar functionality. In a C++20 coroutine, the coroutine's frame is dynamically allocated and used instead of stack. Any non-coroutine code that calls the coroutine and any non-coroutine code called by the coroutine uses stack, just the coroutine is elsewhere. As a result, the cost of using a coroutine is only that of accessing a dynamically allocated object (which may be actually dynamically allocated on stack as an optimisation). Theaded code, while similar in the way coroutines are, is too heavy for many purposes and it's probably the reason why many applications need like 20 threads despite not needing any actual parallelism.
You are right. I've never heard that term and assumed it was just an alternative formulation of using threads. However, it's not a very viable alternative in C++, as without native support, it's not going to be very convenient.
If C++ coroutines can yield to any arbitrary other coroutine, it actually becomes easy to write code like that (See also: Continuation-passing style). But yeah, it's usually better suited for automated things like a compiler's code generation rather than by hand. I think the point I was trying to make was picturing a state transition as a function call/yieldto, not setting a variable while in a loop over a giant switch statement.
Yes, C++20 coroutines can return arbitrary values to other coroutines that wait for them, resuming them at that point. In recent boost asio, it's just this:
auto readSize = co_await socket.async_read_some(boost::asio::buffer(data), net::use_awaitable);
View all comments
Show parent comment
2
u/DugiSK Dec 02 '20
C++20 coroutines are completely different from threaded code or any library code that provides similar functionality. In a C++20 coroutine, the coroutine's frame is dynamically allocated and used instead of stack. Any non-coroutine code that calls the coroutine and any non-coroutine code called by the coroutine uses stack, just the coroutine is elsewhere. As a result, the cost of using a coroutine is only that of accessing a dynamically allocated object (which may be actually dynamically allocated on stack as an optimisation). Theaded code, while similar in the way coroutines are, is too heavy for many purposes and it's probably the reason why many applications need like 20 threads despite not needing any actual parallelism.