【问题标题】:How to make asynchronous call with timeout如何使用超时进行异步调用
【发布时间】:2013-05-29 07:08:53
【问题描述】:

我想在 C++ 中使用超时进行异步调用,这意味着我想实现这样的目标。

AsynchronousCall(function, time);
if(success)
    //call finished succesfully
else
    //function was not finished because of timeout

编辑:其中函数是一种需要大量时间的方法,我想在需要太多时间时中断它。 我一直在寻找如何实现它,我认为boost::asio::deadline_timer 是要走的路。我想调用timer.async_wait(boost::bind(&A::fun, this, args)) 是我需要的,但我不知道如何查找调用是成功还是由于超时而中止。

编辑:在 ForEveR 的回答之后,我的代码现在看起来像这样。

    boost::asio::io_service service;
boost::asio::deadline_timer timer(service);
timer.expires_from_now(boost::posix_time::seconds(5));
timer.async_wait(boost::bind(&A::CheckTimer, this, boost::asio::placeholders::error));
boost::thread bt(&A::AsynchronousMethod, this, timer, args);  //asynchronous launch

void A::CheckTimer(const boost::system::error_code& error)
{
if (error != boost::asio::error::operation_aborted)
{
    cout<<"ok"<<endl;
}
// timer is cancelled.
else
{
    cout<<"error"<<endl;
}
}

我想通过引用传递计时器并在异步方法结束时取消它,但是我收到一个错误,我无法访问在类 ::boost::asio::basic_io_object 中声明的私有成员。

也许使用截止时间计时器不是个好主意?我真的很感激任何帮助。我将定时器传递给函数,因为调用异步方法的方法本身是异步的,因此我不能为整个类或类似的东西设置一个定时器。

【问题讨论】:

    标签: c++ asynchronous timeout boost-asio


    【解决方案1】:

    你应该使用boost::asio::placeholders::error

    timer.async_wait(boost::bind(
    &A::fun, this, boost::asio::placeholders::error));
    
    A::fun(const boost::system::error_code& error)
    {
       // timeout, or some other shit happens
       if (error != boost::asio::error::operation_aborted)
       {
       }
       // timer is cancelled.
       else
       {
       }
    }
    

    【讨论】:

    • 我包含了 boost/asio/placeholders.hpp,但我仍然找不到 boost::asio::placeholders::error :/ 也是 fun 函数的主要工作,应该在函数的开始?
    • @cygi1989 嗯...乐趣就是定时器回调。无论错误如何,它都做了什么?如果找不到 placeholders::error,请尝试简单地使用 _1。
    • 好的,所以我可能误解了deadline_timer的用法。我想异步调用一个函数 A::fun 。这个函数做了很多工作,如果时间太长我想中断这个函数。
    • @cygi1989 设置定时器,然后异步调用该函数。函数执行后(可能在函数末尾)调用timer.cancel(),然后处理程序将使用operation_aborted 信号执行,如果发生超时,将使用success 执行。但是,boost::asio 不是用于异步工作,而是用于一些互联网工作。
    • 我编辑了问题,但仍然不知道它应该如何工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2018-05-27
    相关资源
    最近更新 更多