As the boost document stated here, boost::asio::io_context::run() function blocks until all work has finished and there are no more handlers to be dispatched, or until the io_context has been stopped.
Now I am confused why my code located before one more handler dispatching (t.join()) was not executed until all the handlers completed their works.
I have tried the boost asio tutorial Timer.5 - Synchronising handlers in multithreaded programs
And I added one line code following the io.run():
int main()
{
boost::asio::io_context io;
printer p(io);
boost::thread t(boost::bind(&boost::asio::io_context::run, &io));
io.run();
std::cout << "between run and join" << std::endl;
t.join();
return 0;
}
Here are the console outputs:
Timer 2: 0
Timer 1: 1
Timer 2: 2
Timer 1: 3
Timer 1: 4
Timer 2: 5
Timer 2: 6
Timer 1: 7
Timer 2: 8
Timer 1: 9
between run and join
Final count is 10
I wonder why t.join() was executed before my std::cout << "between run and join" << std::endl;
code? I expect the output "between run and join" to be before all the 2nd thread's outputs.
I think I must be lost at something.