Is steady_clock monotonic across threads?

随声附和 提交于 2019-12-10 13:22:46

问题


Are monotonic properties of std::chrono::steady_clock preserved across threads? For example, suppose I have the following program.

#include <chrono>
#include <mutex>
#include <thread>

using namespace std;
using namespace chrono;

mutex m;
int i = 0;

void do_something(int &x) {
  x += 1;
}

void f1() {
  unique_lock<mutex> lock(m);
  auto time = steady_clock::now();
  do_something(i);
}

void f2() {
  unique_lock<mutex> lock(m);
  auto time = steady_clock::now();
  do_something(i);
}

int main() {
  thread t1(f1);
  thread t2(f2);
  t1.join();
  t2.join();
  return 0;
}

Can I assume that the thread that has the smaller time value in the end (supposing they have different value at all) modified i before the other and that the other saw i as it was left by the first one?


回答1:


Standard [time.clock.steady]

...
static constexpr bool is_steady = true;
static time_point now() noexcept;
...  

is_steady has to be true in all implementations (ie. the class can not exist with false, if the OS etc. isn't capable of it), and both members are independent of instances.

Standard [time.clock.req]:

Clock requirements
...
C1 and C2 denote clock types. t1 and t2 are values returned by C1::now() where the call returning t1 happens before (1.10) the call returning t2 and both of these calls occur before C1::time_-point::max().
...
C1::is_steady: true if t1 <= t2 is always true and the time between clock ticks is constant, otherwise false.

And the 1.10 part contains:

Multi-threaded executions and data races
...
An evaluation A happens before an evaluation B if:
A is sequenced before B, or
A inter-thread happens before B.
...
An evaluation A inter-thread happens before an evaluation B if
A synchronizes with B, or ...

I don't think synchronizing needs to be copied here (a mutex should be enough to fulfil that),
so: Yes, it's ok.



来源:https://stackoverflow.com/questions/40930541/is-steady-clock-monotonic-across-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!