clock_nanosleep() uses the wrong clock to determine the start time point
Original author: sebastian.huber
See gcc-patches mailing list:
On 22/06/2022 08:22, Sebastian Huber wrote:
> On 22/06/2022 08:01, Alexandre Oliva via Gcc-patches wrote:
>>
>> On rtems under qemu, the frequently-interrupted nanosleep ends up
>> sleeping shorter than expected, by a margin of less than 0,3%.
>>
>> I figured failing the library test over a system (emulator?) bug is
>> undesirable, so I put in some tolerance for the drift.
>>
>> Regstrapped on x86_64-linux-gnu, also tested with a cross to
>> aarch64-rtems6. Ok to install?
>>
>> PS: I see nothing wrong with the implementation of clock_nanosleep (used
>> by nanosleep) on rtems6 that could cause it to wake up too early. I
>> suspect some artifact of the emulation environment.
>>
>>
>> for libstdc++-v3/ChangeLog
>>
>> * testsuite/30_threads/this_thread/60421.cc: Tolerate a
>> slightly early wakeup.
>> ---
>> .../testsuite/30_threads/this_thread/60421.cc | 3 ++-
>> 1 file changed, 2 insertions(+), 1 deletion(-)
>>
>> diff --git a/libstdc++-v3/testsuite/30_threads/this_thread/60421.cc b/libstdc++-v3/testsuite/30_threads/this_thread/60421.cc
>> index 12dbeba1cc492..f3a5af453c4ad 100644
>> --- a/libstdc++-v3/testsuite/30_threads/this_thread/60421.cc
>> +++ b/libstdc++-v3/testsuite/30_threads/this_thread/60421.cc
>> @@ -51,9 +51,10 @@ test02()
>> std::thread t([&result, &sleeping] {
>> auto start = std::chrono::system_clock::now();
>> auto time = std::chrono::seconds(3);
>> + auto tolerance = std::chrono::milliseconds(10);
>> sleeping = true;
>> std::this_thread::sleep_for(time);
>> - result = std::chrono::system_clock::now() >= (start + time);
>> + result = std::chrono::system_clock::now() + tolerance >= (start + time);
>> sleeping = false;
>> });
>> while (!sleeping)
>
> This looks like a bug in RTEMS or the BSP for the test platform. I would first investigate this and then change the test which looks all right to me.
This is a problem in RTEMS. RTEMS uses the FreeBSD timecounters to maintain CLOCK_REALTIME and provides two methods to get the time in a coarse and fine resolution. The std::chrono::system_clock::now() uses the fine resolution (higher overhead). The clock_nanosleep() uses the coarse resolution which may give a time before now().
Edited by Amar Takhar