2016-05-22 22 views
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_; 
}; 
+0

请发表[mcve] –

回答

1

DictionaryImpl的io_service在停止工作时会停止。您可以使用asio::io_service::work来防止这种情况。

~DictionaryImpl您致电io_service致电stop后致电reset。唯一一次你想这样做的是,如果你打算随后重新启动io_service

看起来你会从重温文档(这是我接受的是有点稀疏)受益。看看asio文档中的多线程示例。他们将显示使用work对象的示例。

相关问题