0

I'm reading some of the answers regarding Asio and a pattern that stands out, both in examples and here in SO, is to use a single io_service and share it between workers that would handle opening, sending and receiving messages over sockets.

Are there any benefits in sharing an io_service between multiple socket abstractions? Why not let each have their own io_service?

Community
  • 1
  • 1
ruipacheco
  • 15,025
  • 19
  • 82
  • 138
  • Resources. You should try to find existing answers because it's so frequently asked – sehe Nov 06 '16 at 23:12
  • The pattern I normally use is to have one main io_service for all critical work, which has multiple threads dispatching on it. And a secondary io_service for background stuff (admin tasks/sockets etc.) which is normally handled by a single thread. This separation allows me to control for example where things run - and de-prioritize non-critical activity... but it *depends* on what your situation is.. – Nim Nov 09 '16 at 14:21

2 Answers2

1

As far as I understand it, the io_service "owns" the resource. If you have one io_service handling all asio functions, then you can manage priorities. If you have multiple io_service instances, all "owning" the same resource, then they will clash.

Stewart
  • 4,356
  • 2
  • 27
  • 59
  • It's not really that way. E.g. if you have a socket this is not permanently owned by an `io_service`. You could freely use one `io_service` to write data and another to read data. Or perform consecutive async reads through multiple io_services. Which basically equals moving the socket from one io_service to another. The thing which you however should not do is concurrent operations on the resource through multiple io_services. – Matthias247 Nov 11 '16 at 09:47
1

I tried that pattern and would not recommend you to use it anymore expect for only some very specific scenarios. Instead I recommend the "use a socket always only from a single io_service" approach, and using multiple io_services (each running in a dedicated thread) if you have the need for it.

The reason for this is that if you use one io_service from multiple threads all your callbacks (completion handlers) can be invoked from any of the participating threads, and you have to provide additional synchronization for them. In the "resource belongs to one io_service which is executing on one thread" model you don't need this, since no concurrent handlers will be executed from another thread.

Matthias247
  • 9,836
  • 1
  • 20
  • 29