相关疑难解决方法(0)

boost asio async_write:如何不交错async_write调用?

这是我的实现:

  • 客户端A为客户端B发送消息
  • 服务器通过async_read适当数量的数据处理消息,并等待来自客户端A的新数据(为了不阻止客户端A)
  • 随后服务器将处理该信息(可能是做一个MySQL查询),然后将消息发送到客户端B async_write.

问题是,如果客户端A发送消息的速度非常快,async_writes则会在调用前一个async_write处理程序之前进行交错.

有一种简单的方法可以避免这个问题吗?

编辑1:如果客户端C刚刚在客户端A之后向客户端B发送消息,则应出现相同的问题...

编辑2:这会有用吗?因为它似乎阻止了,我不知道在哪里......

 namespace structure {                                                              
  class User {                                                                     
  public:                                                                          
    User(boost::asio::io_service& io_service, boost::asio::ssl::context& context) :
      m_socket(io_service, context), m_strand(io_service), is_writing(false) {}    

    ssl_socket& getSocket() {                                                      
      return m_socket;                                                             
    }                                                                              

    boost::asio::strand getStrand() {                                              
      return m_strand;                                                             
    }                                                                              

    void push(std::string str) {                                                   
      m_strand.post(boost::bind(&structure::User::strand_push, this, str));        
    }                                                                              

    void strand_push(std::string str) {                                            

      std::cout << "pushing: " << boost::this_thread::get_id() << std::endl;       
      m_queue.push(str);                                                           
      if (!is_writing) {                                                           
        write();                                                                   
        std::cout << "going to write" << std::endl;                                
      }                                                                            
      std::cout << "Already writing" …
Run Code Online (Sandbox Code Playgroud)

c++ asynchronous boost-asio

26
推荐指数
2
解决办法
2万
查看次数

标签 统计

asynchronous ×1

boost-asio ×1

c++ ×1