Search code examples
c++multithreadingsystem-clock

Can anyone clarify: Is steady_clock trustworthy between threads in C++


Can anyone please confirm (or deny) whether the steady_clock is "trustworthy" between threads? According to the article Is the epoch of steady_clock relative to when the operating system starts? or to the process itself?, there was some discussion about whether or not the steady_clock was trustworthy at the system level, between processes. My question is, is the steady_clock at least trustworthy between threads?


Solution

  • I believe the relevant part of the standard, [time.clock.req], dictates that the clock type dictates the epoch so, as long as you're using steady_clock, threads are irrelevant:

    A clock is a bundle consisting of a duration, a time_point, and a function now() to get the current time_point. The origin of the clock’s time_point is referred to as the clock’s epoch.

    It would be a poor state of affairs if you couldn't reliably get a duration by subtracting two time_point variables just because one was generated in a separate thread :-)

    Note that this only applies within the scope of the standard. Since the question you linked to was to do with separate processes, the standard does not mandate behaviour one way or another.

    This is no different to writing a binary time_point (or even an int) and expecting it to be the same when reading it back on a totally different system (for example, writing a little-endian int and trying to read it back on a big-endian system).

    But the standard does cover threading so you can safely treat different time_point variable from the same clock type as being compatible.