Lost in threads - how can I extend this example correctly?

放肆的年华 提交于 2019-12-25 06:46:04

问题


I am adapting this example to check if a message has taken too long to receive.

read_complete is called, when read_start has finished. However, I have to check, if the received data is complete and interpret it as incomplete, if it is not fully received in a given time.

These are my extensions to the code above in code/pseudocode:

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();
}

I did state a similar question here How can I setup a deadline_timer in this environment?, but now I already got my timer working - it is just about the threading issue. So, if this is the problem, close the older question, but please not this one.

My main problem is, how do I get to do ResetPacketTimer, so that:

  • I catch any packet that took longer than 10sec
  • Don't think I catched one, when another packet has already been partially received before the 10secs of the first one ran out (hence clearBuffer was not called yet)

来源:https://stackoverflow.com/questions/13089110/lost-in-threads-how-can-i-extend-this-example-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!