C++ io_service,为什么以及如何使用它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/717239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:55:19  来源:igfitidea点击:

io_service, why and how is it used?

c++boostboost-asio

提问by Milan

Trying to learn asio, and I'm following the examples from the website.

尝试学习 asio,我正在关注网站上的示例。

Why is io_service needed and what does it do exactly? Why do I need to send it to almost every other functions while performing asynchronous operations, why can't it "create" itself after the first "binding".

为什么需要 io_service 以及它究竟做了什么?为什么我需要在执行异步操作时将它发送到几乎所有其他函数,为什么它不能在第一次“绑定”之后“创建”自己。

回答by Edu Felipe

Asio's io_serviceis the facilitator for operating on asynchronous functions. Once an async operation is ready, it uses one of io_service's running threads to call you back. If no such thread exists it uses its own internal thread to call you.

Asioio_service是操作异步函数的促进者。一旦异步操作准备就绪,它就会使用 的其中一个io_service正在运行的线程给您回电。如果不存在这样的线程,它会使用自己的内部线程来调用您。

Think of it as a queue containing operations. It guarantees you that those operations, when run, will only do so on the threads that called its run()or run_once()methods, or when dealing with sockets and async IO, its internal thread.

将其视为包含操作的队列。它向您保证,这些操作在运行时只会在调用其run()run_once()方法的线程上执行,或者在处理套接字和异步 IO(其内部线程)时执行。

The reason you must pass it to everyone is basically that someone has to wait for async operations to be ready, and as stated in its own documentation io_serviceis ASIO's link to the Operating System's I/O service so it abstracts away the platform's own async notifiers, such as kqueue, /dev/pool/, epoll, and the methods to operate on those, such as select().

您必须将其传递给所有人的原因基本上是有人必须等待异步操作准备就绪,并且正如其自己的文档中所述,io_serviceASIO 链接到操作系统的 I/O 服务,因此它抽象了平台自己的异步通知程序,如kqueue/dev/pool/epoll,并且这些方法对那些,如操作select()

Primarily I end up using io_service to demultiplex callbacks from several parts of the system, and make sure they operate on the same thread, eliminating the need for explicit locking, since the operations are serialized. It is a very powerful idiom for asynchronous applications.

主要是我最终使用 io_service 对来自系统多个部分的回调进行多路分解,并确保它们在同一线程上运行,消除了显式锁定的需要,因为这些操作是序列化的。对于异步应用程序来说,这是一个非常强大的习惯用法。

You can take a look at the core documentationto get a better feeling of why io_serviceis needed and what it does.

您可以查看核心文档以更好地了解为什么io_service需要它以及它的作用。