steady_clock 跨线程是单调的吗?

Is steady_clock monotonic across threads?

std::chrono::steady_clock 的单调属性是否跨线程保留?例如,假设我有以下程序。

#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;
}

我可以假设最后具有较小 time 值的线程(假设它们具有不同的值)先于另一个修改 i 并且另一个看到 i 因为它是第一个留下的?

标准[time.clock.steady]

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

is_steady 在所有实现中都必须为 true(即 class 不能与 false 一起存在,如果 OS 等不能这样做),并且两个成员都独立于实例。

标准 [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.

1.10 部分包含:

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 ...

我认为不需要在这里复制同步(一个互斥量应该足以实现),
所以:,没关系。