I have 2 processes (not threads) that are supposed to read the system clock at the same time. For this purpose, the first process uses
QTime::currentTime();
and the second process uses
std::chrono::high_resolution_clock::now();
But when I read the respective clock values read by these 2 processes, I find that there's always a difference of a few microseconds. Is it because the system clock is a shared resource, so one has to wait for the other to finish reading? Is it because the functions that read the system clock are not the same, so the time resolution is not the same? (but this seems very unlikely to me... because in my understanding the time resolution is set by the RTC, not the high level APIs)
I do not use any specific 'measure' to synchronize these 2 processes. The first is constantly attempting to read the system clock (it has a while(1)), the second reads the system clock when I launch it. So because the first process is always attempting to read the system clock, I guess there will probably be a 'race condition' when process 2 attempts the read the clock.
There is only a race condition in the sense that you can not predict which process will report an earlier time, or if they will report the same time. No harm is done by (near) simultaneous reads of the clock. Both reports will be accurate to within the ability of the OS to deliver the information. Depending on the OS, and hardware, it may or may not be possible for the two processes to report the same time.
It may or may not be a shared resource. It might not even be the same clock under the hood. std::chrono::high_resolution_clock
is typically a typedef
to either std::chrono::steady_clock
or std::chrono::system_clock
, and which one it is varies by platform. On macOS/iOS/watchOS high_resolution_clock
is a typedef
to steady_clock
and counts nanoseconds since the system booted. This measure has no relationship to the time of day, or date on the calendar.
There is a description of the difference between steady_clock
and system_clock
here.