我已经很久没有成功了。
想象一下,你的主要功能有点像这样:
bool running = true;
int i = 0;
//waitHandler();
while(running)
i++;
现在我想添加并调用一个计时器,它将运行设置为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;
}
当然这不起作用(当你取消评论上面的评论时), 因为计时器会阻塞主线程。 该怎么办,如果我想要在没有阻止主要功能的情况下拥有此功能。
修改
//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;
}
}
}
如上所述,这几乎表明了所希望的行为,但也存在一些问题:
run_one
,也可以触发定时器的处理程序和接收的处理程序 实际上pakets收到错误的顺序,因为它们出现在Wireshark中 - 我想它与async_receive
有关,它不会真正等待收到的消息,但只是接受了函数调用前的缓冲区。
怎么办?
答案 0 :(得分:4)
你正在使它变得比它需要的复杂得多。此网站上有piles of questions处理超时,Boost.Asio网站上有fantastic example。 async_tcp_client示例中的注释有一个很好的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.
//
您应该努力在您的应用程序中实现类似的设计。没有必要像你在问题中发布的那样编写read_with_timeout()
函数来喋喋不休。使用async_read()
,async_write()
和async_wait()
就足以为您提供所需的功能。
我认为你的混淆部分出现在线程上。不要考虑它,首先要理解基本概念。您将需要使用单个线程(调用main()
)和单个io_service
来启动。之后,您可以浏览more advanced concepts。如果您尝试将此代码集成到更大的应用程序中,那完全是一个不同的问题。
学习proactor design pattern也可能对您有所帮助。
答案 1 :(得分:1)
您可以在单独的线程中执行io_service::run
(并以某种方式同步对running
的访问权限)或在io_service
循环内手动取消while
循环,使用{ {3}} - 适用于您的情况。
答案 2 :(得分:0)
我找到了某种解决方案。即使有些事我不明白,我也很满意。
//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;
}
}
}
这实际上适用于我的案例,取自http://lists.boost.org/Archives/boost/2007/04/120339.php 由此主题引用:How to set a timeout on blocking sockets in boost asio?
我刚刚将其改编为Boost 1.51。
有些事情仍然模糊不清,比如说。
无论如何,我的问题到目前为止已经解决了。
答案 3 :(得分:-1)
您必须在自己的线程上生成计时器,然后确保保护正在运行的变量不受并发访问的影响。