boost学习与应用笔记之一:Boost.Atomic

Presenting Boost.Atomic

Boost.Atomic is a library that provides atomic data types and operations on these data types, 
as well as memory ordering constraints required for coordinating multiple threads through atomic variables.
It implements the interface as defined by the C++11 standard, but makes this feature available for platforms lacking system/compiler support for this particular C++11 feature.
Boost.Atomic是一个提供了原子数据类型和操作,以及需要通过原子变量协调多个线程实现内存排序约束的库。
它实现了C++11标准中定义的接口,而且使得不支持或缺乏C++11功能的平台也具有这个功能。

Users of this library should already be familiar with concurrency in general, 
as well as elementary concepts such as "mutual exclusion".
通常,对这个库的使用前你需要比较熟悉并行机制,以及基本的概念,如“互斥”。

The implementation makes use of processor-specific instructions 
where possible (via inline assembler, platform libraries or compiler intrinsics), 
and falls back to "emulating" atomic operations through locking.
它的实现会有可能会要使用特殊性的处理器指令,如(通过内联汇编,平台库或编译器指令),
这有可能会导致它需要通过锁来实现“模拟”的原子操作.

Purpose
Operations on "ordinary" variables are not guaranteed to be atomic. 
This means that with int n=0 initially, two threads concurrently executing
通常,对普通变量的操作是不受原子操作保护的
这意味着,如果对变量进行如下的定义和初始化,
int n = 0;
当有两个线程并行进行下面的操作时:
void function()
{
  n ++;
}

might result in n==1 instead of 2: 
Each thread will read the old value into a processor register, 
increment it and write the result back. Both threads may therefore write 1, 
unaware that the other thread is doing likewise.
会导致结果是 n==1, 而不是n==2.
因为每个线程都是去读取处理器寄存器中的旧值,对其加一后再写回。
这样,有可能两个线程都有是写读到零,写回的一,而没有感知到其它的线程已经做过了.

Declaring atomic<int> n=0 instead, 
the same operation on this variable will always result in n==2 as each operation on this variable is atomic: 
This means that each operation behaves as if it were strictly sequentialized with respect to the other.
对n进行如下声明和初始化后:
atomic<int> n=0;
再用两个线程对这个变量进行操作时,因为它是原子变量,其结果是n==2; 
这意味着,所有对它的操作都是严格序列化的.
简单来说,就是对变量实现了锁保护;

Atomic variables are useful for two purposes:
as a means for coordinating multiple threads via custom coordination protocols
as faster alternatives to "locked" access to simple variables
原子变量有两个用处:
. 通过定制化的协作协议书来实现协同工作队的多线程;
. 更快地替代"锁"来访问简单变量;
它的一些应用示例: http://www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html

你可能感兴趣的:(boost学习与应用笔记之一:Boost.Atomic)