Calling boost::asio::io_service::run from a std::thread
Asked Answered
F

3

9

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

Fireworm answered 9/6, 2014 at 1:39 Comment(0)
M
16

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)));
Marmara answered 9/6, 2014 at 2:21 Comment(2)
Lambda is the way to go here, thanks! Definitely the cleanest looking solution.Fireworm
io_context.run() can be used instead of io_service.run().Yellowgreen
C
1

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)));
Coucal answered 20/3, 2017 at 8:38 Comment(0)
N
1

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(); });
Names answered 13/6, 2019 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.