0
我想运行udp服务器。问题是阻止io_service上的run()调用。 所以我决定在其他线程上使用boost绑定运行此方法。 结果主线程执行超出了DictionaryImpl构造函数的范围,但是当我发送udp包时,tcpdump告诉我我的端口无法访问。 当我在主线程中调用run()调用io_service时,一切正常。 问题在哪里?如何在其他线程中运行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_;
};
请发表[mcve] –