线程中的steady_clock是否单调? [英] Is steady_clock monotonic across threads?

查看:97
本文介绍了线程中的steady_clock是否单调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::chrono::steady_clock的单调特性是否在线程之间保留?例如,假设我有以下程序.

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

我可以假设最后具有较小time值的线程(假设它们根本具有不同的值)在另一个线程之前修改了i,并且另一个线程看到了i,因为该线程保留了第一个?

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?

推荐答案

标准[time.clock.steady]

Standard [time.clock.steady]

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

is_steady在所有实现中都必须为true(即,如果OS等无法实现,则该类不能与false一起存在),并且这两个成员都独立于实例.

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.

标准[time.clock.req]:

Standard [time.clock.req]:

时钟要求
...
C1和C2表示时钟类型. t1和t2是C1 :: now()返回的值,其中返回t1的调用发生在(1.10)之前,而这两个调用都发生在C1 :: time_-point :: max之前().
...
C1 :: is_steady:如果t1< = t2始终为true,并且时钟滴答之间的时间为常数,则为true,否则为false.

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部分包含:

多线程执行和数据争用
...
如果满足以下条件,则在评估B之前进行评估A:
A在B之前排序,或者
B之前发生线程间中断.
...
如果
求值A发生在求值B之前,则线程间发生线程间 A与B 同步,或者 ...

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.

这篇关于线程中的steady_clock是否单调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆