Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is steady_clock monotonic across threads?

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?

like image 848
Giovanni Mascellani Avatar asked Dec 02 '16 10:12

Giovanni Mascellani


1 Answers

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.

like image 58
deviantfan Avatar answered Oct 29 '22 12:10

deviantfan