gpt4 book ai didi

c++ - steady_clock 跨线程是单调的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:40 27 4
gpt4 key购买 nike

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 在所有实现中都必须为真(即,如果操作系统等不支持该类,则该类不能为假),并且两个成员都独立于实例。

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

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

关于c++ - steady_clock 跨线程是单调的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40930541/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com