- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在研究 Java 书中的并发包。我不太明白这本书中关于 CAS 操作的内容。以下代码示例是本书中的线程安全 counter
类。
public class Counter{
private AtomicInteger count = new AtomicInteger();
public void increment(){
count.getAndIncrement(); //atomic operation
}
....
}
这本书是这样说的。
In reality, even a method such as
getAndIncrement()
still takes several steps to execute. The reason this implementation is now thread-safe is something called CAS. CAS stands for Compare And Swap. Most modern CPUs have a set of CAS instructions. A basic outline of what is happening now is as follows:
- The value stored in count is copied to a temporary variable.
- The temporary variable is incremented.
- Compare the value currently in count with the original value. If it is unchanged, then swap the old value for the new value.
好的,我明白它所说的关于多个步骤的意思了。我不太明白在列举的步骤中发生了什么。
- The value stored in count is copied to a temporary variable.
临时变量在哪里?它在主存储器中,寄存器吗?或者这是特定于 CPU 架构的?
- Compare the value currently in count with the original value. If it is unchanged, then swap the old value for the new value.
原始值存储在哪里?它不能是临时变量。那个正在修改,对吧?我错过了什么?
谢谢
最佳答案
被比较的值被加载到两个以上的寄存器中(在你的例子中是三个)。然后它可能会使用类似 CMPXCHG8B
的指令这被描述(部分)为
Compare EDX:EAX with m64. If equal, set ZF and load ECX:EBX into m64. Else, clear ZF and load m64 into EDX:EAX.
上面的第三个值可能在不同的寄存器中,比如 ECX
(或 EBX
)或其他一些位置(只是不是 EAX
或EDX
)。您可以引用 Compare and Swap 上的维基百科条目对于其他实现(不一定使用汇编程序)。
关于java - 不懂Java原子包中的CAS操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810235/
所以我今天在学习c。我编写了一些代码以使用 getchar() 获取输入并将其保存在变量中以了解整数输入的工作原理。 因此,如果用我的键盘输入“1”,然后按回车键,我会返回 4910 的值。我预计 4
我是一个非常沮丧的新手!我真的不知道从哪里开始。我有一个基于傻瓜书中的应用程序的应用程序。成功了。然后尝试将其转换为使用 WIMMOne 对话框来显示时间和日期。经过一系列错误的启动后,我加载了他们的
我们刚刚使用 bitbucket 建立了一个项目。我们将“生产”[P] 代码放在一个存储库中,然后我创建了它的一个分支 [m],然后我的同事 [C] 也创建了一个分支。 [P] /
我不明白我看到的错误,也不明白我应该在我的 ESLint 配置中更改什么来修复它,在深入研究了一段时间之后。 我有一段使用 ECMA 版本 6 (ES6) 的 JS 代码,如下所示: const la
我的代码有很多问题。编译时出现以下错误: “Ecommerce.DataHelpers.ProductNodeLoader”未实现接口(interface)成员“System.Collections.
我不明白这个语法是如何工作的,也找不到关于它的文档: word = '123xyz567' s = ''.join (c if c.isdigit() else ' 'for c in word) 第
不知道怎么解释,是在IE7中出现的,右边的DIV向右浮动,取消设置它的宽度,左边 float 的子DIV会变成和父DIV一样宽。 http://jsfiddle.net/dyvar/1/ IE 7 最
$newUser.addClass(newTweet.user).attr('data-user', newTweet.user).text('@' + newTweet.user + ': ');
我有一个带有输入框的 tkinter GUI,我只想允许数字。有人可以向我解释验证中每个命令/代码行的作用。我不明白 vcmd 变量和所有 '%i' '%s' 的东西。谢谢:) 更新:我有一个不同的应
我正在尝试使用 Richard Dawkin 的 Weasel Program 的 Python 版本这演示了随机选择与累积选择之间的差异,并且我的变异算法存在一些问题。我想也许我不明白如何使用Pyt
我正在学习嵌套,我的任务是让每一行都以缩进开头。这是我的代码,但它不起作用 $nestingDepth = 0 def logger description, &block puts "Beg
我正在编译 gcc 并阅读来自 https://gcc.gnu.org/install/configure.html 的手册 具体说明 --with-local-prefix=dirname Spec
我是一名优秀的程序员,十分优秀!