简体   繁体   中英

Boost::Asio on Windows doesn't work asynchronously

I am studying a book on Boost, now I am in Asio chapter.

https://theboostcpplibraries.com/boost.asio-scalability

I found some simple example of asynchronous timers. I was very surprised when I noticed on my Windows laptop that the examples work differently than how the author described it.

Here is the code of the example (slightly modified compared to the book, I mean the values of the timers):

#include <boost/asio/io_service.hpp>
#include <boost/asio/steady_timer.hpp>
#include <chrono>
#include <thread>
#include <iostream>

using namespace boost::asio;

int main()
{
  io_service ioservice1;
  io_service ioservice2;

  steady_timer timer1{ioservice1, std::chrono::seconds{3}};
  timer1.async_wait([](const boost::system::error_code &ec)
    { std::cout << "3 sec\n"; });

  steady_timer timer2{ioservice2, std::chrono::seconds{9}};
  timer2.async_wait([](const boost::system::error_code &ec)
    { std::cout << "9 sec\n"; });

  std::thread thread1{[&ioservice1](){ ioservice1.run(); }};
  std::thread thread2{[&ioservice2](){ ioservice2.run(); }};
  thread1.join();
  thread2.join();
}

I expected that I should see first printout on console after 3 secs, and after next 6 seconds I should see the second printout. But on Windows it didn't work this way. The program waited 9 seconds to print both messages at the same time. This should not work this way!

I checked that on Linux everything works fine, as expected.

Does anyone know why there is such difference in behaviour on Windows and Linux? This behaviour on Windows makes the Asio unusable, it does not work asynchronously.

Regards YotKay

cout doesn't flush its output immediately by default. Add a << std::endl to the end of each call to cout and see if you get the results you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM