I have a class which handles my connection that has a boost::asio::io_service member. I'm wanting to call io_service::run() from a std::thread, but I am running into compilation errors.
std::thread run_thread(&boost::asio::io_service, std::ref(m_io_service));
Does not work. I see various examples out there for doing this using boost::thread, but I am wanting to stick to std::thread for this. Any suggestions?
Thanks
There are two ways as I have known, one is to create std::thread by lambda.
std::thread run_thread([&]{ m_io_service.run(); });
Another is to create boost::thread with boost::bind
boost::thread run_thread(boost::bind(&boost::asio::io_service::run, boost::ref(m_io_service)));
Just extending a bit on @cbel's answer. Another way of doing it if you (for whatever reason) would like to avoid boost::thread and lambdas:
std::thread run_thread(
std::bind(static_cast<size_t(boost::asio::io_service::*)()>(
&boost::asio::io_service::run), std::ref(m_io_service)));
For me, both options for the answer marked as the solution did result in exceptions.
What did it for me was:
boost::thread run_thread([&] { m_io_service.run(); });
instead of
std::thread run_thread([&]{ m_io_service.run(); });
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