简体   繁体   English

在多个线程上使用单个io_service有什么好处?

[英]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. 我读了一些关于短耳和脱颖而出的图形的答案,无论是在实例和这里的SO,是使用单一io_service对象,并且将处理开放,发送和通过套接字接收消息工人之间分享。

Are there any benefits in sharing an io_service between multiple socket abstractions? 在多个套接字抽象之间共享io_service有什么好处? Why not let each have their own io_service? 为什么不让每个人都有自己的io_service?

As far as I understand it, the io_service "owns" the resource. 据我了解,io_service“拥有”资源。 If you have one io_service handling all asio functions, then you can manage priorities. 如果您有一个io_service处理所有asio函数,则可以管理优先级。 If you have multiple io_service instances, all "owning" the same resource, then they will clash. 如果您有多个“拥有”相同资源的io_service实例,则它们将发生冲突。

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. 相反,我建议“始终仅从单个io_service使用套接字”方法,如果需要,请使用多个io_services(每个都在专用线程中运行)。

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. 原因是,如果您从多个线程中使用一个io_service,则可以从任何参与线程中调用所有回调(完成处理程序),并且必须为其提供额外的同步。 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. 在“资源属于在一个线程上执行的一个io_service”模型中,您不需要这样做,因为不会从另一个线程执行并发处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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