【发布时间】:2023-03-15 01:42:01
【问题描述】:
对于互斥体lock(),标准的mentions:
同一互斥体上的先前 unlock() 操作与(定义在 std::memory_order 中)此操作同步。
这个answer 试图根据标准解释synchronize-with 的含义。但是,看起来定义没有明确规定。
我的主要问题是,我能得到这个输出吗:
x: 1
y: 2
对于由于线程 A 中的内存重新排序而导致的以下代码?如果在A 解锁后B 锁定,A 中的x 上的写入是否保证被B 观察到?
std::mutex mutex;
int x = 0, y = 0;
int main() {
std::thread A{[] {
x = 1;
std::lock_guard<std::mutex> lg(std::mutex);
y = 0;
}};
std::thread B{[] {
std::lock_guard<std::mutex> lg(std::mutex);
y = x + 2;
}};
A.join();
B.join();
std::cout << "x: " << x << std::endl;
std::cout << "y: " << y << std::endl;
}
如果不是,基于标准的哪一部分? 换句话说,我们可以假设锁定/解锁之间存在顺序一致性吗?
我也看到了这个related 问题,但它是针对单独的互斥锁的。
【问题讨论】:
-
您的代码具有 UB,因为从
x读取的内容不与对x的写入内容独占。因此,我认为无法对内存排序进行推理。一旦允许 UB,标准就不再适用。但是一旦你解决了这个问题,那么事情肯定会被定义,1 2输出将是不可能的。否则 1.10/10 不会成立。 -
如果状态 S1 和 S2 之间存在竞争,为什么我们不能推理是否处于状态 S3(即 1 2)?我认为这个问题是:stackoverflow.com/questions/62164376/…
标签: c++ multithreading mutex