作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试运行 udp 服务器。问题是阻塞了 io_service 上的 run() 调用。所以我决定使用 boost bind 在其他线程上运行这个方法。结果主线程执行超出了 DictionaryImpl 构造函数范围,但是当我发送 udp 包时,tcpdump 告诉我我的端口无法访问。当我在主线程中调用 run() 调用 io_service 时,一切正常。问题出在哪里?
class DictionaryImpl {
boost::asio::io_service io;
boost::scoped_ptr<boost::thread> thread;
public:
DictionaryImpl() {
try {
udp_server2 udpReceiver(io);
thread.reset(new boost::thread(
boost::bind(&DictionaryImpl::g, this, std::ref(io))));
} catch (std::exception &e) {
std::cerr << "Exception: " << e.what() << "\n";
}
}
void g(boost::asio::io_service & io){
io.run();
}
virtual ~DictionaryImpl() {
if (!thread) return; // stopped
io.stop();
thread->join();
io.reset();
thread.reset();
}
};
class udp_server2
{
public:
udp_server2(boost::asio::io_service& io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13003))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server2::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_receive(const boost::system::error_code& error,
std::size_t /*bytes_transferred*/)
{
if (!error || error == boost::asio::error::message_size)
{
std::cout<<"handle_receive\n";
start_receive();
}
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array<char, 1> recv_buffer_;
};
最佳答案
DictionaryImpl
的 io_service 会在用完工作时停止。您可以使用 asio::io_service::work
来防止这种情况。
在 ~DictionaryImpl
中,您在 io_service
上调用 stop
之后调用 reset
。只有在您计划随后重新启动 io_service
时,您才会这样做。
看起来你会从重新访问文档中受益(我承认它有点稀疏)。也可以看看 asio 文档中的多线程示例。他们将展示使用 work
对象的示例。
关于c++ - 如何在其他线程中运行 io_service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376685/
我是一名优秀的程序员,十分优秀!