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

语法

¥Syntax

js
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)

参数

¥Parameters

typedArray

整数类型数组。Int8ArrayUint8ArrayInt16ArrayUint16ArrayInt32ArrayUint32ArrayBigInt64ArrayBigUint64Array 之一。

index

typedArray 的位置换成 replacementValue

expectedValue

用于检查相等性的值。

replacementValue

要交换的号码。

返回值

¥Return value

给定位置 (typedArray[index]) 的旧值。如果返回值等于 expectedValue,则交换成功;否则,交换失败。

¥The old value at the given position (typedArray[index]). If the return value is equal to expectedValue, the exchange was successful; otherwise, the exchange failed.

例外情况

¥Exceptions

TypeError

如果 typedArray 不是允许的整数类型之一,则抛出该错误。

RangeError

如果 indextypedArray 中出界,则抛出该球。

示例

¥Examples

使用 compareExchange()

¥Using compareExchange()

js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 7;

Atomics.compareExchange(ta, 0, 7, 12); // returns 7, the old value
Atomics.load(ta, 0); // 12

检查返回值

¥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:

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看