Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use io_service::work?

I'm new in boost programming, and I've been looking for a reason to use the io_service::work, but I can't figure it out; in some of my tests I removed it and works fine.

like image 573
lucastamoios Avatar asked Nov 04 '12 14:11

lucastamoios


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 io_ service in c++?

The io_service class provides the core I/O functionality for users of the asynchronous I/O objects, including: asio::ip::tcp::socket. asio::ip::tcp::acceptor. asio::ip::udp::socket. deadline_timer .

How do I stop IO service boost?

Stopping the io_service from running out of work boost::asio::io_service io_service; boost::asio::io_service::work work(io_service); ... To effect a shutdown, the application will then need to call the io_service object's stop() member function.


1 Answers

The io_service::run() will run operations as long as there are asynchronous operations to perform. If, at any time, there are no asynchronous operations pending (or handlers being invoked), the run() call will return.

However, there are some designs that would prefer that the run() call not exit until all work is done AND the io_service has explicitly been instructed that it's okay to exit. That's what io_service::work is used for. By creating the work object (I usually do it on the heap and a shared_ptr), the io_service considers itself to always have something pending, and therefore the run() method will not return. Once I want the service to be able to exit (usually during shutdown), I will destroy the work object.

like image 94
Dave S Avatar answered Oct 05 '22 06:10

Dave S