0

I'm working on an application in which I want to use boost::beast/asio. I need to receive data via a websocket connection and issue requests to a REST API at the same time.

In the boost::beast websocket/HTTP async client examples it seems like the next async operation is started in the completion handlers. This seems to give rise to the same "callback hell" I've seen in node.js applications.

To avoid this I'm thinking of using a simple state machine in my application to decide what operation to start next. I'm thinking of having a while loop in my application where I call poll() on the io_context after which I run my state machine code (e.g. switch(state) { ... state = nextState; } )

However this might create a busy loop in which the main thread consumes 100% cpu while it constantly runs the state machine?

Is my reasoning correct and would it be better to use something like post() to queue a functor which would advance the state machine?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
b20000
  • 995
  • 1
  • 12
  • 30

1 Answers1

1

I wish I could leave this as a comment since it's not really a full answer, but I don't have enough reputation to comment.

If you're talking about node.js, I assume you have some experience with 'promises' and/or the newer 'async/await' - at least that's how node.js avoids callback hell.

Turns out Boost Asio has something similar to node.js 'async/await'. It's called Boost Asio Coroutines and you implement it the exact same way as node.js 'async/await'.

Not sure if it's a good idea to run a while loop which consumes 100% of the thread? That's a bit of a waste when there are better solutions.

rmlds
  • 61
  • 3
  • thanks for your reply. I hate the whole node.js approach with promises and async await. It's super confusing and I cannot see myself building any decent size application with that. A state machine has the advantage of bringing the logic together in one place, which is much better than having it scattered over countless callbacks. I know that promises can be chained but for me it doesn't solve anything. It just introduces a bunch of syntax that obfuscates what's really going on. – b20000 Jan 12 '19 at 07:06
  • I am unfamiliar with javascript, but I do like the coroutines in boost::asio. They behave quite a lot like blocking IO on threads, but with much much less of the overhead. Your function just gets suspended when executing the call, until the result is back, you don't have to supply a callback. – Martijn Otto Jan 22 '19 at 13:19