C++ 内存模型

问题描述 投票:0回答:0

我一直在探索 C++ 的世界,我对以下问题很感兴趣。我对正式答案感兴趣(带有指向 C++ 标准的链接以确认您的答案)。我希望你会对这个不简单的问题感兴趣:)

所以

A
是一些全球性的
std::atomic<int>
varibale。其他线程只读它。

void foo() {
  // here A != 42
  A.store(42, std::memory_order::relaxed);
  auto a = A.load(std::memory_order::relaxed);
  if (a != 42) assert("What!?")
}

一些线程调用

foo()
。什么语言规则保证
A.store(42, ...)
发生在之前(更准确地说,
sequenced before
A.load(...)
在称为“foo”的线程中?

现在让我们将某些

B
添加到问题条件中。这也是一些全球性的
std::atomic<int>
变量。

现在

foo()
函数看起来像这样:

void foo() {
  // here A != 42
  A.store(42, std::memory_order::relaxed);
  B.store(0, std::memory_order::seq_cst);
  auto a = A.load(std::memory_order::relaxed);
  if (a != 42) assert("What!?")
}

在 x64 上,我可以确定这样的代码等同于(除了我们不更改

B
:D):

void foo() {
  // here A != 42
  A.store(42, std::memory_order::relaxed);
  std::atomic_thread_fence(std::memory_order::seq_cst);
  auto a = A.load(std::memory_order::relaxed);
  if (a != 42) assert("What!?")
}

但是从C++语言标准的角度来看,有这样的保证吗?

c++ multithreading language-lawyer atomic memory-model
© www.soinside.com 2019 - 2024. All rights reserved.