user406009
user406009

Reputation:

Thread safe coroutines with asio

Is there any way I can have thread-safe coroutines along with boost::asio?

I want one io_service to be running on multiple threads and to have some of my handlers be coroutines.

Boost.Coroutine would seem to be a solution, but they document that they do not support resuming a coroutine that was started in a separate thread.

As far as I know there are only two possible solutions to this problem:

  1. Don't use coroutines. Use the much more verbose(even with lambda), but equally functional method of chaining callbacks that store state.
  2. Force each handler to only run in one thread. I know this is possible by simply having a separate io_service for each thread. As an aside, is there an easy way, similar to io_service::strand, to force a set of handlers to run in the same thread?

Neither are in any way good solutions. In one solution I lose coroutines. In the other I lose most of my multithreading ability.

Upvotes: 9

Views: 2375

Answers (1)

user406009
user406009

Reputation:

It seems that this problem has no easy solution.

The main problem is probably due to the fact that C++ allows compilers to reorder most of what happens in a function. Thus you cannot reliably depend on the order of things happening in functions.

It looks like I am going to have to end up using a series of callbacks, possibly using lambda's if I have a desire to keep everything looking semantically like a block of code.

Perhaps I can even hack something up using macros that resolves to lambdas to simulate the coroutine style.

Upvotes: 3

Related Questions