c++ std::memory_order

1. Relaxed ordering: 在单个线程内,所有原子操作是顺序进行的。两个来自不同线程的原子操作是任意顺序的。

2. Release -- acquire: 来自不同线程的两个原子操作顺序限制,需要两个线程进行一下同步(synchronize-with)。同步对一个变量的读写操作。线程 A 原子性地把值写入 x (release), 然后线程 B 原子性地读取 x 的值(acquire). 这样线程 B 保证读取到 x 的最新值。

store-release, load-acquire 用法示例代码

// atomic::load/store example
#include <iostream>       // std::cout
#include <atomic>         // std::atomic, std::memory_order_relaxed
#include <thread>         // std::thread

std::atomic<int> foo (0);

void set_foo(int x) {
  foo.store(x,std::memory_order_release);     // set value atomically
}

void print_foo() {
  int x;
  do {
    x = foo.load(std::memory_order_acquire);  // get value atomically
  } while (x==0);
  std::cout << "foo: " << x << '
';
}

int main ()
{
  std::thread first (print_foo);
  std::thread second (set_foo,10);
  first.join();
  second.join();
  return 0;
}

  

原文地址:https://www.cnblogs.com/rayfloyd/p/14306356.html