Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7893600
  • 博文数量: 701
  • 博客积分: 2150
  • 博客等级: 上尉
  • 技术积分: 13233
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-29 16:28
个人简介

天行健,君子以自强不息!

文章分类

全部博文(701)

文章存档

2019年(2)

2018年(12)

2017年(76)

2016年(120)

2015年(178)

2014年(129)

2013年(123)

2012年(61)

分类: C/C++

2016-04-10 10:13:32

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 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 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
原子变量有两个用处:
. 通过定制化的协作协议书来实现协同工作队的多线程;
. 更快地替代"锁"来访问简单变量;
它的一些应用示例:
阅读(3331) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~