簡體   English   中英

std :: condition_variable :: wait_until的實現

[英]implementation of std::condition_variable::wait_until

我正在閱讀std::condition_variable::wait_until的libstdc ++ 實現 ,這里是源代碼:

template<typename _Clock, typename _Duration>
  cv_status
  wait_until(unique_lock<mutex>& __lock,
     const chrono::time_point<_Clock, _Duration>& __atime)
  {
    // DR 887 - Sync unknown clock to known clock.
    const typename _Clock::time_point __c_entry = _Clock::now();
    const __clock_t::time_point __s_entry = __clock_t::now();
    const auto __delta = __atime - __c_entry;
    const auto __s_atime = __s_entry + __delta;

    return __wait_until_impl(__lock, __s_atime);
  }

template<typename _Clock, typename _Duration, typename _Predicate>
  bool
  wait_until(unique_lock<mutex>& __lock,
     const chrono::time_point<_Clock, _Duration>& __atime,
     _Predicate __p)
  {
    while (!__p())
      if (wait_until(__lock, __atime) == cv_status::timeout)
        return __p();
    return true;
  }

第二個函數調用循環中的第一個函數。它將執行時鍾同步操作。如果我們調用第二個函數,同步操作可能會運行多次。每次都需要同步時鍾嗎?我認為代碼可以改進在第二個功能中只通過同步時鍾一次。對吧?

我覺得你是對的。 另一方面,使用wait_until的假設通常是事件將只是稀疏地發生,並且除了少數不必要的喚醒之外,謂詞返回true。 因此,重新同步時鍾的開銷應該是最小的。 還要記住,在這種情況下,線程必須已經被喚醒並且已經被分頁,這可能比查詢時鍾更昂貴。

是的,不。

是的,這個代碼可以優化,以便在循環時不操縱time_point 但是,我不確定這是否真的有必要。

考慮是什么使得謂詞wait_until循環。

通知后 ,它會檢查謂詞以查看是否有工作要做。

  1. 如果謂詞返回true,即條件變量保護的條件為真,則wait_until返回true
  2. 如果超時過去, wait_until將返回謂詞的值,該值通常為false (否則我們會預期condition_variable wait_until變量已被通知)。

這只留下一個循環實際循環的情況:當通知condition_variable ,謂詞返回false

這被稱為虛假喚醒並不是典型的情況,所以它並不值得優化。

暫無
暫無

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

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