jaredready
jaredready

Reputation: 2678

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

Upvotes: 9

Views: 9193

Answers (3)

Tom Vos
Tom Vos

Reputation: 420

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(); });

Upvotes: 1

jpihl
jpihl

Reputation: 8071

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)));

Upvotes: 1

cbel
cbel

Reputation: 1077

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)));

Upvotes: 16

Related Questions