I have implemented the following function:
bool ResponsiveSleep(atomic<bool>& flag, const float nSeconds, const float grainSec=0.1f)
{
auto tpUntil = chrono::steady_clock::now() + chrono::duration<float>(nSeconds);
while (chrono::steady_clock::now() < tpUntil) {
if (flag.load(memory_order::acquire)) {
return true;
}
this_thread::sleep_for(chrono::duration<float>(grainSec));
}
return flag.load(memory_order::acquire);
}
And I'm calling it like this to sleep for 5 seconds:
atomic<bool> flag = false;
cout << "Start sleeping: " << double(clock()) / CLOCKS_PER_SEC << endl;
TimeUtils::ResponsiveSleep(flag, 5);
cout << "Stop sleeping: " << double(clock()) / CLOCKS_PER_SEC << endl;
However, I am getting random sleeps of 20 to 40 seconds. System: Windows 10, MSVC++ 2019 v16.5.3
Could you help to troubleshoot this? I have a guess that chrono::duration<float>(x)
doesn't really expect number of seconds as x
, however earlier I found examples suggesting that.
Aucun commentaire:
Enregistrer un commentaire