compareAndExchange 与 compareAndExchangeAcquire 之间有什么区别
What is the difference between compareAndExchange vs compareAndExchangeAcquire
这是来自 Java 库的片段:
public final boolean compareAndExchangeAcquire(boolean expectedValue, boolean newValue) {
return (int)VALUE.compareAndExchangeAcquire(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0)) != 0;
}
来自AtomicBoolean
class。怎么才能把a转换成int
return a boolean
?
我的主要问题:compareAndExchange
和 compareAndExchangeAcquire
有什么区别?
通俗地说:在 xxxAcquire
之前和 xxxRelease
之后编写的语句在应用 xxx
.
时可以自由重新排序
您发布的代码的最后一部分是 != 0
。使用澄清变量:
int a = (int)VALUE.compareAndExchangeAcquire(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0));
return a != 0;
当然 !=
运算符 returns 是一个布尔值。
关于问题的第二部分:
Also, what is the difference between compareAndExchange vs compareAndExchangeAcquire?
首先是一些必读:
从上面的回答你应该明白compilers/processors可以对loads/stores重新排序,获取和释放的限制就在上面。比较和交换很可能是用 CAS 指令实现的,可以将其视为加载+存储。 compareAndExchangeAcquire
和 compareAndExchangeRelease
将 release/acquire 语义添加到有问题的 CAS/load+ 商店。换句话说,您可以使用这些来防止某些重新排序,或允许某些重新排序。
这是来自 Java 库的片段:
public final boolean compareAndExchangeAcquire(boolean expectedValue, boolean newValue) {
return (int)VALUE.compareAndExchangeAcquire(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0)) != 0;
}
来自AtomicBoolean
class。怎么才能把a转换成int
return a boolean
?
我的主要问题:compareAndExchange
和 compareAndExchangeAcquire
有什么区别?
通俗地说:在 xxxAcquire
之前和 xxxRelease
之后编写的语句在应用 xxx
.
您发布的代码的最后一部分是 != 0
。使用澄清变量:
int a = (int)VALUE.compareAndExchangeAcquire(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0));
return a != 0;
当然 !=
运算符 returns 是一个布尔值。
关于问题的第二部分:
Also, what is the difference between compareAndExchange vs compareAndExchangeAcquire?
首先是一些必读:
从上面的回答你应该明白compilers/processors可以对loads/stores重新排序,获取和释放的限制就在上面。比较和交换很可能是用 CAS 指令实现的,可以将其视为加载+存储。 compareAndExchangeAcquire
和 compareAndExchangeRelease
将 release/acquire 语义添加到有问题的 CAS/load+ 商店。换句话说,您可以使用这些来防止某些重新排序,或允许某些重新排序。