簡體   English   中英

如何使用超時進行異步調用

[英]How to make asynchronous call with timeout

我想在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類中聲明的私有成員。

也許使用截止時間計時器不是一個好主意嗎? 我真的很感謝您的幫助。 我將計時器傳遞給該函數,因為調用異步方法的方法本身就是異步的,因此我不能為整個類或某物設置一個計時器。

您應該使用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
   {
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM