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?
auto
is just shorthand to instruct the compiler to automatically infer the type so that I do not have to type it. Assume you havesteady_clock::time_point
instead ofauto
if you do not like it. Of course the variable is automatic and so is discarded at the end of the thread, but suppose I have some way to report it and decide, comparing the timestamps, which thread executed before. Can I have guarantee from thesteady_clock
monotonicity? – Jamnessteady_clock
makes the guarantee that it never does, meaning that if you call it twice the first call will return a value which is not greater than the second. But I do not understand whether this guarantees extends across different threads, and that is what I am asking. – Jamnesi
is not atomic, you have a race condition. Therefore, your corollary that the thread that has the smaller time value ... modifiedi
before the other and that the other sawi
as it was left by the first one is not correct; instead, you have undefined behavior. – Herculean