模板类std::atomic<T>介绍

  头文件#include,使用方法atomic val;
  原子类型对象的主要特点是从不同线程访问共享数据,不会导致数据竞争(data race)。数据竞争,简单而言就是,假设线程th1对共享数据进行了修改,而当线程th2对该共享数据进行访问时,其结果是未知的,可能是修改之前的值,也有可能是修改之后的值。

Threads and data races

  A thread of execution is a flow of control within a program that begins with the invocation of a top-level function by std::thread::thread, std::async, or other means.
  Any thread can potentially access any object in the program (objects with automatic and thread-local storage duration may still be accessed by another thread through a pointer or by reference).
  Different threads of execution are always allowed to access (read and modify) different memory locations concurrently, with no interference and no synchronization requirements.
  When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race unless

  • both evaluations execute on the same thread or in the same signal handler, or
  • both conflicting evaluations are atomic operations (see std::atomic), or
  • one of the conflicting evaluations happens-before another (see std::memory_order)

  If a data race occurs, the behavior of the program is undefined.
  (In particular, release of a std::mutex is synchronized-with, and therefore, happens-before acquisition of the same mutex by another thread, which makes it possible to use mutex locks to guard against data races.)

int cnt = 0;
auto f = [&]{cnt++;};
std::thread t1{f}, t2{f}, t3{f}; // undefined behavior
std::atomic<int> cnt{0};
auto f = [&]{cnt++;};
std::thread t1{f}, t2{f}, t3{f}; // OK

Introduction from cppreference.com

  Each instantiation and full specialization of the std::atomic template defines an atomic type. If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races).
  In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by std::memory_order.
  std::atomic is neither copyable nor movable.
在这里插入图片描述

Introduction from cplusplus.com

  Objects of atomic types contain a value of a particular type (T).
  The main characteristic of atomic objects is that access to this contained value from different threads cannot cause data races (i.e., doing that is well-defined behavior, with accesses properly sequenced). Generally, for all other objects, the possibility of causing a data race for accessing the same object concurrently qualifies the operation as undefined behavior.
  Additionally, atomic objects have the ability to synchronize access to other non-atomic objects in their threads by specifying different memory orders.

参考

  1. https://en.cppreference.com/w/cpp/atomic/atomic
  2. http://www.cplusplus.com/reference/atomic/atomic/?kw=atomic

更新中…

你可能感兴趣的:(C++学习,C++,atomic)