Atomics.compareExchange()
如果给定的期望值等于旧值,则 Atomics.compareExchange()
静态方法会在数组中的给定位置处交换给定的替换值。它返回该位置的旧值,无论它是否等于预期值。此原子操作保证在修改的值被写回之前不会发生其他写入。
¥The Atomics.compareExchange()
static method exchanges a given replacement value at a given position in the array, if a given expected value equals the old value. It returns the old value at that position whether it was equal to the expected value or not. This atomic operation guarantees that no other write happens until the modified value is written back.
Try it
语法
参数
¥Parameters
typedArray
-
整数类型数组。
Int8Array
、Uint8Array
、Int16Array
、Uint16Array
、Int32Array
、Uint32Array
、BigInt64Array
或BigUint64Array
之一。 index
-
把
typedArray
的位置换成replacementValue
。 expectedValue
-
用于检查相等性的值。
replacementValue
-
要交换的号码。
返回值
例外情况
示例
使用 compareExchange()
检查返回值
¥Checking the return value
比较和交换 保证新值是根据最新信息计算的;如果在此期间另一个线程已更新该值,则写入将失败。因此,你应该检查 compareExchange()
的返回值以检查它是否失败,并在必要时重试。
¥Compare-and-swap 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. Therefore, you should check the return value of compareExchange()
to check if it has failed, and retry if necessary.
以下是原子加法器(与 Atomics.add()
功能相同)的一个示例,改编自链接的 Wikipedia 文章:
¥Here is one example of an atomic adder (same functionality as Atomics.add()
), adapted from the linked Wikipedia article:
function add(mem, index, value) {
let done = false;
while (!done) {
const value = Atomics.load(mem, index);
done = Atomics.compareExchange(p, value, value + a) === value;
}
return value + a;
}
它首先读取给定索引处的值,然后尝试使用新值更新它。它会不断重试,直到成功更新值。
¥It first reads the value at the given index, then tries to update it with the new value. It keeps retrying until it successfully updates the value.
规范
Specification |
---|
ECMAScript Language Specification # sec-atomics.compareexchange |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also