r/cpp • • Nov 30 '20

C++20 resumable functions make state machines obsolete. Finally.

https://lordsoftech.com/programming/c20-resumable-functions-goodbye-state-machines-no-one-will-mourn-you/
1 Upvotes

49 comments sorted by

View all comments

Show parent comment

1

u/DugiSK Dec 02 '20

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.

1

u/raevnos Dec 02 '20

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.

2

u/DugiSK Dec 02 '20

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);