Reputation: 371
Consider the chat example at : http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/examples.html
Look the client file : http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/example/chat/chat_client.cpp
Here, seems like the point at which boost thread which runs the io_service is important..
chat_client c(io_service, iterator);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
If I create the thread before I create an object of chat_client, then the io_service.stopped() returns true if printed in the while loop below that.
I do not understand why it is so?
Upvotes: 1
Views: 1590
Reputation: 20918
What is io_service::run()
doing ?
The run() function blocks until all work has finished and there are no more handlers to be dispatched, or until the io_service has been stopped.
when you call async function like (async_read,async_write, ...) you need to pass handlers to these functions. Handlers are called when async operation will be done. In io_service::run()
async operations are being processed.
Before calling io_service::run
at least one async operation must be waiting for executing. If you call io_service::run
when there are no async operations planned, this method returns immediately. So
io_service::run
in thread to process async operationsio_service::run
works (this method runs as long as there are async operations)Look at constructor of chat_client
socket_.async_connect(endpoint,
boost::bind(&chat_client::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
async_connect
method is invoked - this is first async operation to be executed.
io_service::stopped()
returns true when io_service::run
ends working because there are no async operations to be processed.
A normal exit from the run() function implies that the io_service object is stopped (the stopped() function returns true).
Upvotes: 2