首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

[转]CAS的含意及Java中AtomicXXX类的分析

2012-09-07 
[转]CAS的含义及Java中AtomicXXX类的分析维基百科:In computer science, the compare-and-swap CPU instru

[转]CAS的含义及Java中AtomicXXX类的分析
维基百科:
In computer science, the compare-and-swap CPU instruction ("CAS") (or the Compare & Exchange - CMPXCHG instruction in the x86 and Itanium architectures) is a special instruction that atomically (regarding intel x86, lock prefix should be there to make it really atomic) compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value. This guarantees that the new value is calculated based on up-to-date information; if the value had been updated by another thread in the meantime, the write would fail. The result of the operation must indicate whether it performed the substitution; this can be done either with a simple Boolean response (this variant is often called compare-and-set), or by returning the value read from the memory location (not the value written to it). Compare-and-Swap (and Compare-and-Swap-Double) has been an integral part of the IBM 370(and all successor) architectures since 1970. The operating systems which run on these architectures make extensive use of Compare-and-Swap (and Compare-and-Swap-Double) to facilitate process (i.e., system and user tasks) and processor (i.e., central processors) parallelism while eliminating, to the greatest degree possible, the "disabled spin locks" which were employed in earlier IBM operating systems. In these operating systems, new units of work may be instantiated "globally", into the Global Service Priority List, or "locally", into the Local Service Priority List, by the execution of a single Compare-and-Swap instruction. This dramatically improved the responsiveness of these operating systems.
===================================================
总结:CAS是硬件CPU提供的元语,它的原理:我认为位置 V 应该包含值 A;如果包含该值,则将 B 放到这个位置;否则,不要更改该位置,只告诉我这个位置现在的值即可。
Java并发库中的AtomicXXX类均是基于这个元语的实现,以AtomicInteger为例:

int current = get(); int next = current + 1;


由于valatile只能保证读取或写入的是最新值,那么可能出现以下情况:
1 A线程执行get()操作,获取current值(假设为1)
2 B线程执行get()操作,获取current值(为1)
3 B线程执行next = current + 1操作,next = 2
4 A线程执行next = current + 1操作,next = 2
这样的结果明显不是我们想要的,所以,自增操作必须采用CAS来完成。

热点排行