调用boost::asio::io_service::从std::线程中运行

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

本文关键字:std 线程 运行 boost asio io 调用 service      更新时间:2023-10-16

我有一个类来处理我的连接,它有一个boost::asio::io_service成员。我想从std::线程调用io_service::run(),但是我遇到了编译错误。

std::thread run_thread(&boost::asio::io_service, std::ref(m_io_service));

不起作用。我看到了很多使用boost::thread来做这件事的例子,但是我想坚持使用std::thread。有什么建议吗?

谢谢

我知道有两种方法,一种是通过lambda创建std::thread。

std::thread run_thread([&]{ m_io_service.run(); });
另一种方法是用boost::bind 创建boost::线程
boost::thread run_thread(boost::bind(&boost::asio::io_service::run, boost::ref(m_io_service)));

只是对@cbel的回答进行了一点扩展。如果您(无论出于何种原因)想要避免boost::thread和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)));

对于我来说,标记为解决方案的答案的两个选项都导致例外。

对我起作用的是:

boost::thread run_thread([&] { m_io_service.run(); });
不是

std::thread run_thread([&]{ m_io_service.run(); });