简体   繁体   English

std::memory_order_relaxed 与 fetch_add

[英]std::memory_order_relaxed with fetch_add

I'm trying gain a deeper understanding of relaxed memory ordering.我正在尝试更深入地了解轻松的 memory 订购。 Per CPP reference, there is no synchronization, however atomicity is still guaranteed.根据 CPP 参考,没有同步,但原子性仍然得到保证。 Doesn't atomicity in this case require some form of sync, eg how does fetch_add() below guarantee that only one thread will update the value from y to y+1 , particularly if writes can be visible out of order to different threads?在这种情况下,原子性不需要某种形式的同步,例如,下面的fetch_add()如何保证只有一个线程会将值从y更新为y+1 ,特别是如果写入对于不同线程来说是无序可见的? Is there an implicit sync associated with fetch_add ?是否有与fetch_add关联的隐式同步?

memory_order_relaxed Relaxed operation: there are no synchronization or ordering constraints imposed on other reads or writes, only this operation's atomicity is guaranteed (see Relaxed ordering below) memory_order_relaxed Relaxed 操作:没有对其他读取或写入施加同步或顺序约束,仅保证此操作的原子性(请参阅下面的 Relaxed ordering)

#include <thread>
#include <iostream>
#include <atomic>
#include <vector>
#include <cassert>

using namespace std;

static uint64_t incr = 100000000LL;

atomic<uint64_t> x;

void g()
{
   for (long int i = 0; i < incr; ++i)
   {
      x.fetch_add(1, std::memory_order_relaxed);
   }
}

int main()
{
   int Nthreads = 4;
   vector<thread> vec;
   vec.reserve(Nthreads);
   for (auto idx = 0; idx < Nthreads; ++idx)
      vec.push_back(thread(g));
   for(auto &el : vec)
      el.join();
   // Does not trigger
   assert(x.load() == incr * Nthreads);
}

"Synchronization" has a very specific meaning in C++. “同步”在C++中有非常具体的含义。

It refers to following.它指的是跟随。 Let's say:比方说:

  1. Thread A reads/writes to memory X. (doesn't have to be atomic)线程 A 读取/写入 memory X。(不必是原子的)

  2. Thread A writes to atomic variable Y. (must be a release or seq_cst write)线程A写入原子变量Y。(必须是release或者seq_cst写)

  3. Thread B reads the variable Y, and sees the value previously written by A. (must be an acquire or seq_cst read)线程 B 读取变量 Y,并看到 A 之前写入的值。(必须是acquireseq_cst读取)

    At this point, operations (2) and (3) are said to synchronize with each other.此时,操作 (2) 和 (3) 被称为彼此同步

  4. Thread B reads/writes to memory X. (doesn't have to be atomic)线程 B 读取/写入 memory X。(不必是原子的)

    Normally this would cause a data race with thread A (undefined behavior), but it doesn't because of the synchronization.通常这会导致与线程 A 的数据争用(未定义的行为),但不会因为同步而发生。

This only works with release / acquire / seq_cst operations, and not relaxed operations.这仅适用于release / acquire / seq_cst操作,不适用于relaxed操作。 That's what the quote means.这就是报价的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM