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".
注意:此操作仅适用于查看
SharedArrayBuffer的Int32Array或BigInt64Array,并且在主线程上可能不允许。有关此方法的非阻塞异步版本,请参阅Atomics.waitAsync()。¥Note: This operation only works with an
Int32ArrayorBigInt64Arraythat views aSharedArrayBuffer, and may not be allowed on the main thread. For a non-blocking, asynchronous version of this method, seeAtomics.waitAsync().
语法
参数
¥Parameters
typedArray-
查看
SharedArrayBuffer的Int32Array或BigInt64Array。 index-
在
typedArray的位置等待。 value-
要测试的期望值。
timeoutOptional-
等待时间以毫秒为单位。
NaN(以及转换为NaN的值,例如undefined)变为Infinity。负值变为0。
返回值
例外情况
¥Exceptions
TypeError-
有下列情况之一的,抛出:
- 如果
typedArray不是观看SharedArrayBuffer的Int32Array或BigInt64Array。 - 如果当前线程无法被阻塞(例如,因为它是主线程)。
- 如果
RangeError-
如果
index在typedArray中出界,则抛出该球。
示例
使用 wait()
¥Using wait()
给定一个共享的 Int32Array:
¥Given a shared Int32Array:
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).
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:
console.log(int32[0]); // 0;
Atomics.store(int32, 0, 123);
Atomics.notify(int32, 0, 1);
规范
| Specification |
|---|
| ECMAScript Language Specification # sec-atomics.wait |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also