Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling boost::asio::io_service::run from a std::thread

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

like image 692
jaredready Avatar asked Jun 09 '14 01:06

jaredready


3 Answers

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)));
like image 117
cbel Avatar answered Nov 04 '22 04:11

cbel


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)));
like image 1
jpihl Avatar answered Nov 04 '22 02:11

jpihl


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(); });
like image 1
Tom Vos Avatar answered Nov 04 '22 02:11

Tom Vos