简体   繁体   中英

Whats the benefit of using a single io_service over multiple threads?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM