My prefered way to use an io_service
is to create a thread on application start that executes the io_service
's run method. The problem is, if there is no task for io_service
, its run method returns immediately and the thread terminates.
As you can see from the chat_client.cpp
...
boost::asio::io_service io_service;
...
chat_client c(io_service, iterator);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
the thread is started after some async task is added to io_service
. This is done in the chat_clients
's constructor.
My question is: Is there a way to create the thread before some task is added to io_service
, i. e.
// create io_service and thread on application start
boost::asio::io_service io_service;
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
// add some task to io_service
chat_client c(io_service, iterator);
As you said, its run method returns immediately because it has no work. You need to use boost::asio::io_service::work . Think of it as a dummy work item, so io_service::run never runs out of work, and thus doesn't return immediately.
Example:
auto work = boost::make_shared<boost::asio::io_service::work>(m_ioservice);
m_ioservice.run();
Some people prefer an io_service::run to always block, waiting for work. Other people prefer the behavior Asio gives you by default.
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