c++ - memory_order_relaxed 有哪些用例

标签 c++ memory-model

C++ 内存模型放宽了原子性,不对内存操作提供任何顺序保证。除了我在这里找到的 C 中的邮箱示例:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1525.htm

基于本文中的激励示例:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2153.pdf

我很好奇这种同步机制的其他用例。

最佳答案

我在工作中经常看到的一个简单示例是统计计数器。如果你 想要计算事件发生的次数但不需要任何类型的 除了使增量安全之外,还可以使用跨线程同步 memory_order_relaxed 是有道理的。

static std::atomic<size_t> g_event_count_;

void HandleEvent() {
  // Increment the global count. This operation is safe and correct even
  // if there are other threads concurrently running HandleEvent or
  // PrintStats.
  g_event_count_.fetch_add(1, std::memory_order_relaxed);

  [...]
}

void PrintStats() {
  // Snapshot the "current" value of the counter. "Current" is in scare
  // quotes because the value may change while this function is running.
  // But unlike a plain old size_t, reading from std::atomic<size_t> is
  // safe.
  const size_t event_count =
      g_event_count_.load(std::memory_order_relaxed);

  // Use event_count in a report.
  [...]
}

在这两种情况下,都不需要使用更强的内存顺序。一些 平台,这样做可能会对性能产生负面影响。

关于c++ - memory_order_relaxed 有哪些用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23487372/

相关文章:

c++ - 格式错误的 C 或 C++ 程序是否保证在 Visual Studio 中的 DEBUG 配置下崩溃

c++ - 如何将屏幕截图位图转换为 cv::Mat

python线程: memory model and visibility

c++ - 重新排序和 memory_order_relaxed

c++ - 使用 memory_order_relaxed 如何在典型架构上保证原子变量的总修改顺序?

c++ - 在 vector vector 的 vector 中找到最大位置

c++ - alloca 返回的指针的基于索引的访问和 "placement new"的效果

c++ - 如何在 Linux 中使用 C++ 下载受密码保护的 URL?

c++ - 宽松的原子规则有什么(轻微)差异?

c - C 中的字符串常量与 char 数组