迷失在线程中 - 如何正确扩展此示例?

时间:2012-10-26 14:43:39

标签: c++ boost boost-asio boost-thread

我正在调整this example以检查邮件是否花了太长时间才能收到。

read_complete完成时,会调用

read_start。但是,我必须检查,如果收到的数据是完整的,如果在给定时间内没有完全收到,则将其解释为不完整。

这些是我在代码/伪代码中对代码的扩展:

void read_complete(const boost::system::error_code& error, size_t bytes_transferred)
{ // the asynchronous read operation has now completed or failed and returned an error
  if (!error)
  { // read completed, so process the data
    cout.write(read_msg_, bytes_transferred); // echo to standard output
    MyOnReceivedData(MyHandle someHandle, numOfBytes);
    read_start(); // start waiting for another asynchronous read again
  }
  else do_close(error);
} 

void MyOnReceivedData(MyHandle someHandle,int numOfBytes){
  ResetPacketTimer();
  \\check if whole packet was received
  if (wholePacket){    
    MyOnReceivedPacket(someHandle);    
  }
}

void MyOnReceivedPacket(MyHandle someHandle){
  cout << "packet"
  clearBuffer(someHandle);   
}

void MyOnPacketTimeout(MyHandle someHandle){
   cout << "we're in";
   if (!bufferEmpty(someHandle)){
     cout << "timeout";
   }
}

void ResetPacketTimer(MyHandle someHandle){
    boost::asio::io_service io;
    boost::asio::deadline_timer t(io, boost::posix_time::milliseconds(10000));

    t.async_wait(boost::bind(&MyOnPacketTimeout, someHandle);
    //this works async, but MyOnPacketTimeout is not called
    boost::thread t2(boost::bind(&boost::asio::io_service::run, &io));
    //this works, but not async - app waits for 10 secs
    //io.run();
}

我确实在How can I setup a deadline_timer in this environment?说了一个类似的问题,但现在我已经让我的计时器正常工作了 - 这只是一个线程问题。所以,如果这是问题,请关闭旧问题,但请不要这个。

我的主要问题是,如何做ResetPacketTimer,以便:

  • 我抓住任何花费超过10秒的数据包
  • 当第一个数据包的10secs用完之前已经部分接收到另一个数据包时,我认为没有抓到一个(因此 clearBuffer 尚未被调用)

0 个答案:

没有答案