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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With