简体   繁体   中英

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

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

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