memory_order_relaxed有哪些用例

时间:2014-05-06 06:27:30

标签: 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

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

2 个答案:

答案 0 :(得分:9)

我经常在工作中看到一个简单的例子是统计数据。如果你 想要计算事件发生的次数,但不需要任何类型的事件 除了使增量安全,使用之外,跨线程同步 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.
  [...]
}

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

答案 1 :(得分:0)

在这种情况下,事件读取器可以连接到X11套接字,事件的发生频率取决于用户操作(调整窗口大小,键入等),并且GUI线程的事件分发程序是否定期检查事件(例如,由于用户应用程序中的某些计时器事件),我们不想通过获取已知为空的共享事件队列上的锁来不必要地阻塞事件读取器线程。我们可以简单地通过使用'dataReady'原子检查是否有任何队列。这也称为“双重检查锁定”模式。

npm install less --save-dev