2012-03-27 29 views
1

我正在嘗試使用提升中的timed_wait。現在我其實不太清楚如何做到這一點。從boost中使用timed_wait?

整個事情的目的是確定它的狀態。在下面的代碼中調用了函數getStatus()。這個函數是異步的,如果一切順利,它會調用一個特定的回調函數來表明一切都是好的。如果它沒有及時調用回調(所以發生超時),我知道出了問題。

因此,這裏的示例代碼:

void myClass::checkStatus() 
{ 
    boost::mutex::scoped_lock lock(m_Mutex); 
    boost::condition_variable cond; 
    while(true) 
    { 
     getStatus(); // Async Call to get the actual status 
     if(!cond.timed_wait(lock,boost::posix_time::milliseconds(3000),/* Callback */)) 
     { 
      // Timeout 
     } 
     else 
     { 
      // OK 
     } 
    } 
} 
bool myClass::myCallback() 
{ 
/* ... */ 
} 

所以,你可以看到,我不知道如何恰當地「增加」回調到我的TIMED_WAIT。其實我真的不知道它會如何工作,因爲我希望我的回調是從我的異步線程調用的,而不是從timed_wait本身調用的? (異步線程需要指示一切順利)

我也查看了Boost Documentation,但它無法幫助我更多。

第二個問題:我的互斥鎖在這個例子中總是鎖定..?

回答

3

關於你的第二個問題:在執行timed_wait期間,互斥鎖被鎖定在整個checkStatus函數中,除了。這是關鍵。

我不確定你打算用myCallback是什麼意思。但要檢查狀態,我會將一個狀態成員添加到myClass,將其設置爲getStatus,並在的else分支中檢查它。舉例:

boost::condition_variable m_cond; 

void myClass::checkStatus() 
{ 
    boost::mutex::scoped_lock lock(m_Mutex); 

    while(true) 
    { 
     getStatus(); // Async Call to get the actual status 
     if(!m_cond.timed_wait(lock,boost::posix_time::milliseconds(3000),/* Callback */)) 
     { 
      // Timeout 
     } 
     else 
     { 
      //check status 
      if (m_status == STATUS_1) 
      { 
       // handle STATUS_1 
      } 
      else if (m_status == STATUS_2) 
      { 
       // handle STATUS_2 
      } 
     } 
    } 
} 

void getStatus() 
{ 
    boost::thread myThread(myWorkerFunc); 
} 

void myWorkerFunc() 
{ 
    // do a long running operation to get the status 
    int status = retrieveStatusSomehow(); 

    // lock the same mutex that you used for the condition variable 
    boost::mutex::scoped_lock lock(m_Mutex); 

    // assign the status to member 
    m_status = status; 

    // notify the condition to wake up 
    m_cond.notify_all(); 
} 

我希望現在更清楚。也許你可以在你的回調函數中使用這種方法。你也應該考慮在超時情況下取消後臺線程以避免競爭條件。

編輯:請注意,條件變量必須是一個成員來通知它關於異步操作的結束。

+0

好吧,我想我得到它....會嘗試適應你的方法..我有點感覺,我得到了'提高timed_wait'爲了錯誤的目的(最初我正在尋找'pthread timed_wait' - 那麼現在就試着用你的建議 – Toby 2012-03-27 08:31:53

+0

好的問題:除了timeout之外,'timed_wait'阻塞了多長時間?直到它可以解鎖給定的鎖或者直到notify_all()被調用? – Toby 2012-03-27 09:01:05

+0

這是個好問題。被鎖定,直到調用'notify_all'或'notify_one'爲止,並且它還可以解除[spurious wakups](http://en.wikipedia.org/wiki/Spurious_wakeup)(這是** not **處理通過上面的代碼) – Stephan 2012-03-27 09:10:49