Boost:需要的示例:超时

Boost:需要的示例:超时,boost,timeout,boost-asio,Boost,Timeout,Boost Asio,我已经在这方面做了很长时间,但没有成功 假设您的主要功能如下: bool running = true; int i = 0; //waitHandler(); while(running) i++; 现在我想添加并调用一个计时器,它将running设置为false, 到期时 void waitHandler(){ boost::asio::io_service timerService; //create and bind the timer boost

我已经在这方面做了很长时间,但没有成功

假设您的主要功能如下:

bool running = true;
int i = 0;
//waitHandler();
while(running)
    i++;
现在我想添加并调用一个计时器,它将running设置为false, 到期时

void waitHandler(){ 

    boost::asio::io_service timerService;

    //create and bind the timer
    boost::asio::deadline_timer timer(timerService,
    boost::posix_time::milliseconds(2000));
    timer.wait();

    running = true;
    cout<<"WaitHandler triggered"<<endl;
}
void waitHandler(){
boost::asio::io_服务timerService;
//创建并绑定计时器
boost::asio::截止时间计时器(timerService,
boost::posix_time::毫秒(2000));
timer.wait();
运行=真;

您必须在自己的线程上生成计时器,然后确保保护运行中的变量不受并发访问。

您必须在自己的线程上生成计时器,然后确保保护运行中的变量不受并发访问。

您可以在单独的线程中执行
io_service::run
(以某种方式同步对
正在运行的
)的访问,或在
while
循环中手动泵送
io_服务
循环,在您的情况下使用-任何合适的方法。

您可以在单独的线程中执行
io_服务::run
(以某种方式同步对
正在运行的
的访问)或者在
循环中手动泵送
io_服务
循环,同时在
循环中使用-任何适合您的方法。

我找到了某种解决方案。尽管有些事情我不明白,但我还是同意

//transfer some error message
void set_result(boost::system::error_code* a, boost::system::error_code b,deadline_timer &timer)
  {
     a->assign(b.value(),b.category());
  } 


 template<class SOCKET>
 void read_with_timeout(SOCKET & sock, unsigned int delay,
     const asio::mutable_buffers_1& buffers)
  {       
      //create error messages
      boost::system::error_code timer_result; 
      boost::system::error_code read_result; 

      //initialize timer
      deadline_timer timer(sock.get_io_service());        
      timer.expires_from_now(boost::posix_time::milliseconds(delay));
      timer.async_wait(boost::bind(set_result, &timer_result, _1,boost::ref(timer)));       

      //initialize receive mechanism
      sock.async_receive(buffers, boost::bind(set_result, &read_result, _1,boost::ref(timer)));    
      sock.get_io_service().reset();

      //should run for one handler
      while (sock.get_io_service().run_one())    
      {      
          if (read_result.value()==0){ //zero stands for, that the message was received properly.            
              timer.cancel();
              //cout<<"Message received: => Timer cancelled => RETURN!"<<endl;
              return;
          }

          if(timer.expires_from_now().total_milliseconds() <=0){                
              sock.cancel();                
              //cout<<"Timeout => Socket cancelled => RETURN!"<<endl;         
              return;
          }
      }   
 } 
//传输一些错误消息
无效设置结果(boost::系统::错误代码*a,boost::系统::错误代码b,截止时间计时器和计时器)
{
a->assign(b.value(),b.category());
} 
模板
无效读取超时(套接字和套接字、无符号整数延迟、,
常量asio::可变缓冲区(1和缓冲区)
{       
//创建错误消息
boost::system::error\u code timer\u result;
boost::system::错误代码读取结果;
//初始化定时器
截止日期计时器(sock.get_io_service());
timer.expires_from_now(boost::posix_time::毫秒(延迟));
异步等待(boost::bind(set_result,&timer_result,_1,boost::ref(timer));
//初始化接收机制
异步接收(缓冲区,boost::bind(设置结果,读取结果,1,boost::ref(计时器));
sock.get_io_service().reset();
//应该为一个处理程序运行
while(sock.get\u io\u service().run\u one())
{      
如果(read_result.value()==0){//0表示消息已正确接收。
timer.cancel();

//我已经找到了某种解决办法。尽管有些事情我不明白,但我还是同意

//transfer some error message
void set_result(boost::system::error_code* a, boost::system::error_code b,deadline_timer &timer)
  {
     a->assign(b.value(),b.category());
  } 


 template<class SOCKET>
 void read_with_timeout(SOCKET & sock, unsigned int delay,
     const asio::mutable_buffers_1& buffers)
  {       
      //create error messages
      boost::system::error_code timer_result; 
      boost::system::error_code read_result; 

      //initialize timer
      deadline_timer timer(sock.get_io_service());        
      timer.expires_from_now(boost::posix_time::milliseconds(delay));
      timer.async_wait(boost::bind(set_result, &timer_result, _1,boost::ref(timer)));       

      //initialize receive mechanism
      sock.async_receive(buffers, boost::bind(set_result, &read_result, _1,boost::ref(timer)));    
      sock.get_io_service().reset();

      //should run for one handler
      while (sock.get_io_service().run_one())    
      {      
          if (read_result.value()==0){ //zero stands for, that the message was received properly.            
              timer.cancel();
              //cout<<"Message received: => Timer cancelled => RETURN!"<<endl;
              return;
          }

          if(timer.expires_from_now().total_milliseconds() <=0){                
              sock.cancel();                
              //cout<<"Timeout => Socket cancelled => RETURN!"<<endl;         
              return;
          }
      }   
 } 
//传输一些错误消息
无效设置结果(boost::系统::错误代码*a,boost::系统::错误代码b,截止时间计时器和计时器)
{
a->assign(b.value(),b.category());
} 
模板
无效读取超时(套接字和套接字、无符号整数延迟、,
常量asio::可变缓冲区(1和缓冲区)
{       
//创建错误消息
boost::system::error\u code timer\u result;
boost::system::错误代码读取结果;
//初始化定时器
截止日期计时器(sock.get_io_service());
timer.expires_from_now(boost::posix_time::毫秒(延迟));
异步等待(boost::bind(set_result,&timer_result,_1,boost::ref(timer));
//初始化接收机制
异步接收(缓冲区,boost::bind(设置结果,读取结果,1,boost::ref(计时器));
sock.get_io_service().reset();
//应该为一个处理程序运行
while(sock.get\u io\u service().run\u one())
{      
如果(read_result.value()==0){//0表示消息已正确接收。
timer.cancel();

//cout您正在使这个问题变得比需要的复杂得多。在这个网站上有关于超时的信息,在Boost.Asio网站上有一个。来自async_tcp_客户端示例的注释有一个很好的ASCII图来解释这个场景

// This class manages socket timeouts by applying the concept of a deadline.
// Some asynchronous operations are given deadlines by which they must complete.
// Deadlines are enforced by an "actor" that persists for the lifetime of the
// client object:
//
//  +----------------+
//  |                |
//  | check_deadline |<---+
//  |                |    |
//  +----------------+    | async_wait()
//              |         |
//              +---------+
//
// If the deadline actor determines that the deadline has expired, the socket
// is closed and any outstanding operations are consequently cancelled.
//
// Connection establishment involves trying each endpoint in turn until a
// connection is successful, or the available endpoints are exhausted. If the
// deadline actor closes the socket, the connect actor is woken up and moves to
// the next endpoint.
//
//  +---------------+
//  |               |
//  | start_connect |<---+
//  |               |    |
//  +---------------+    |
//           |           |
//  async_-  |    +----------------+
// connect() |    |                |
//           +--->| handle_connect |
//                |                |
//                +----------------+
//                          :
// Once a connection is     :
// made, the connect        :
// actor forks in two -     :
//                          :
// an actor for reading     :       and an actor for
// inbound messages:        :       sending heartbeats:
//                          :
//  +------------+          :          +-------------+
//  |            |<- - - - -+- - - - ->|             |
//  | start_read |                     | start_write |<---+
//  |            |<---+                |             |    |
//  +------------+    |                +-------------+    | async_wait()
//          |         |                        |          |
//  async_- |    +-------------+       async_- |    +--------------+
//   read_- |    |             |       write() |    |              |
//  until() +--->| handle_read |               +--->| handle_write |
//               |             |                    |              |
//               +-------------+                    +--------------+
//
// The input actor reads messages from the socket, where messages are delimited
// by the newline character. The deadline for a complete message is 30 seconds.
//
// The heartbeat actor sends a heartbeat (a message that consists of a single
// newline character) every 10 seconds. In this example, no deadline is applied
// message sending.
//
//此类通过应用截止日期的概念来管理套接字超时。
//一些异步操作会在最后期限之前完成。
//最后期限是由一个“参与者”强制执行的,该“参与者”将在项目的生命周期内持续执行
//客户端对象:
//
//  +----------------+
//  |                |

//|检查|截止日期|您正在使这个问题变得比需要的复杂得多。在这个网站上有关于超时的信息,在Boost.Asio网站上有一个。来自async|u tcp|u客户端示例的注释有一个很好的ASCII图来解释这个场景

// This class manages socket timeouts by applying the concept of a deadline.
// Some asynchronous operations are given deadlines by which they must complete.
// Deadlines are enforced by an "actor" that persists for the lifetime of the
// client object:
//
//  +----------------+
//  |                |
//  | check_deadline |<---+
//  |                |    |
//  +----------------+    | async_wait()
//              |         |
//              +---------+
//
// If the deadline actor determines that the deadline has expired, the socket
// is closed and any outstanding operations are consequently cancelled.
//
// Connection establishment involves trying each endpoint in turn until a
// connection is successful, or the available endpoints are exhausted. If the
// deadline actor closes the socket, the connect actor is woken up and moves to
// the next endpoint.
//
//  +---------------+
//  |               |
//  | start_connect |<---+
//  |               |    |
//  +---------------+    |
//           |           |
//  async_-  |    +----------------+
// connect() |    |                |
//           +--->| handle_connect |
//                |                |
//                +----------------+
//                          :
// Once a connection is     :
// made, the connect        :
// actor forks in two -     :
//                          :
// an actor for reading     :       and an actor for
// inbound messages:        :       sending heartbeats:
//                          :
//  +------------+          :          +-------------+
//  |            |<- - - - -+- - - - ->|             |
//  | start_read |                     | start_write |<---+
//  |            |<---+                |             |    |
//  +------------+    |                +-------------+    | async_wait()
//          |         |                        |          |
//  async_- |    +-------------+       async_- |    +--------------+
//   read_- |    |             |       write() |    |              |
//  until() +--->| handle_read |               +--->| handle_write |
//               |             |                    |              |
//               +-------------+                    +--------------+
//
// The input actor reads messages from the socket, where messages are delimited
// by the newline character. The deadline for a complete message is 30 seconds.
//
// The heartbeat actor sends a heartbeat (a message that consists of a single
// newline character) every 10 seconds. In this example, no deadline is applied
// message sending.
//
//此类通过应用截止日期的概念来管理套接字超时。
//一些异步操作会在最后期限之前完成。
//最后期限是由一个“参与者”强制执行的,该“参与者”将在项目的生命周期内持续执行
//客户端对象:
//
//  +----------------+
//  |                |

//| check_deadline |我是否总是需要一个独立于使用上述示例中的同步计时器或异步等待的线程?这取决于您尝试执行的操作。如果您尝试在特定时间内执行工作,您还可以在循环开始时获取当前时间,并且每次通过循环时都可以检查自该开始时间以来经过的时间。在elapsedTime>X之后,您可以中断循环。但是,如果您希望程序在后台工作时保持响应,则需要使用线程。async_wait正在为您创建线程,因此您正在为async_wait创建一个方法,以便在等待完成后调用d、 这意味着,实际上,例如timer.async_wait(waitHandler)(不介意语法)是否应该自行创建线程,从而不阻止主线程?@Byron Lim Timothy Steffan
async\u wait
不创建线程,它只是启动一个async.operations。此操作的完成处理程序在
io\u服务
线程上被调用,该线程在您的示例中被阻止。因此使用