Atomics.wait()

Atomics.wait() 静态方法验证共享内存位置是否仍然包含给定值,如果是,则休眠,等待唤醒通知或超时。它返回一个字符串,可以是 "ok""not-equal""timed-out"

¥The Atomics.wait() static method verifies that a shared memory location still contains a given value and if so sleeps, awaiting a wake-up notification or times out. It returns a string which is either "ok", "not-equal", or "timed-out".

注意:此操作仅适用于查看 SharedArrayBufferInt32ArrayBigInt64Array,并且在主线程上可能不允许。有关此方法的非阻塞异步版本,请参阅 Atomics.waitAsync()

¥Note: This operation only works with an Int32Array or BigInt64Array that views a SharedArrayBuffer, and may not be allowed on the main thread. For a non-blocking, asynchronous version of this method, see Atomics.waitAsync().

语法

¥Syntax

js
Atomics.wait(typedArray, index, value)
Atomics.wait(typedArray, index, value, timeout)

参数

¥Parameters

typedArray

查看 SharedArrayBufferInt32ArrayBigInt64Array

index

typedArray 的位置等待。

value

要测试的期望值。

timeout Optional

等待时间以毫秒为单位。NaN(以及转换为 NaN 的值,例如 undefined)变为 Infinity。负值变为 0

返回值

¥Return value

一个字符串,可以是 "ok""not-equal""timed-out"

¥A string which is either "ok", "not-equal", or "timed-out".

例外情况

¥Exceptions

TypeError

有下列情况之一的,抛出:

RangeError

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

示例

¥Examples

使用 wait()

¥Using wait()

给定一个共享的 Int32Array

¥Given a shared Int32Array:

js
const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);

读取线程正在睡眠并等待位置 0,该位置预计为 0。只要这是真的,它就不会继续下去。然而,一旦写入线程存储了新值,它将被写入线程通知并返回新值(123)。

¥A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123).

js
Atomics.wait(int32, 0, 0);
console.log(int32[0]); // 123

写入线程存储新值并在写入后通知等待线程:

¥A writing thread stores a new value and notifies the waiting thread once it has written:

js
console.log(int32[0]); // 0;
Atomics.store(int32, 0, 123);
Atomics.notify(int32, 0, 1);

规范

Specification
ECMAScript Language Specification
# sec-atomics.wait

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看