Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

io_service, why and how is it used?

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

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".

like image 497
Milan Avatar asked Apr 04 '09 15:04

Milan


People also ask

How does boost ASIO work?

At its core, Boost Asio provides a task execution framework that you can use to perform operations of any kind. You create your tasks as function objects and post them to a task queue maintained by Boost Asio. You enlist one or more threads to pick these tasks (function objects) and invoke them.

What is ASIO post?

ASIO library, ASIO stands for asynchronous input/output. This library allows asynchronous processing of data. Asynchronous means that a program doesn't have to wait for completion of an operation to start a new one. It can execute more than one operations concurrently.

What is IO context?

io_context contains state required to run the event loop based on select , epoll , or other platform-specific calls and dispatch events, such as socket readiness, timer, signal, idle, to the callbacks the user has registered. Many callbacks for different sockets, timers, etc.. can be registered with one io_context .


1 Answers

Asio's io_service is 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.

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.

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_service is 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().

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.

You can take a look at the core documentation to get a better feeling of why io_service is needed and what it does.

like image 69
Edu Felipe Avatar answered Sep 25 '22 12:09

Edu Felipe