在 g 11.2.1 下可以看到以下行為。std::condition_variable wait_for如果超時變數太大,該方法會立即回傳。特別是在下面的程式中,如果num_years==1,則程式按預期掛起等待(大概為 1 年),但如果變數num_years==1000則程式立即回傳。
為什么會這樣?這是g 中的錯誤嗎?還有一個相關的問題,你如何讓cv.wait_for()等待無限期,而不是猜測一個大的超時值?
// This is 'cv_wait.cc' compile with:
//
// g -o cv_wait -std=c 2a cv_wait.cc
//
// An example showing that wait_for() returns immediately with a timeout
// return value if the duration variable is "too large".
//
#include <iostream>
#include <condition_variable>
#include <chrono>
int main(int argc, char **argv)
{
std::condition_variable cv;
std::mutex cv_m;
// If num_years is "too large", e.g. 1000, then cv.wait_for()
// returns immediately with a timeout condition!
int num_years = 1; // If 1000 then cv.wait_for() returns immediately!
std::chrono::seconds timeout((uint64_t)3600 * 24 * 365 * num_years);
std::unique_lock<std::mutex> lock(cv_m);
if (cv.wait_for(lock, timeout, [] { return false; }))
std::cerr << "No timeout!\n";
else
std::cerr << "Timeout!\n";
}
uj5u.com熱心網友回復:
這是condition_variable::wait_for. 在內部,它正在等待使用steady_clockwhich counts nanoseconds。這個時鐘在 /-292 年溢位。因此,當 1000 年轉換為 時nanoseconds,它會溢位。
這看起來像一個標準錯誤而不是實作錯誤:http ://eel.is/c draft/thread.condition#condvar-24
實作應該檢查這種型別的溢位,如果發現,只需等待它能夠等待的最長時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425949.html
