Atomics
Atomics 对象提供了一组静态方法对 SharedArrayBuffer 和 ArrayBuffer 对象进行原子操作。
code
import { isMainThread, parentPort, Worker } from 'worker_threads';
function main() {
var w: Worker = new Worker(__filename);
w.once('online', () => {
console.log('子线程上线');
var sab = new SharedArrayBuffer(4);
setTimeout(() => {
w.postMessage(sab);
setTimeout(() => {
console.log('尝试唤醒...');
var modify = new Int32Array(sab);
Atomics.notify(modify, 0);
}, 6000);
}, 2000);
});
}
if (isMainThread) {
main();
} else {
task();
}
function task() {
console.log('我是子进程');
var flag = false;
parentPort.once('message', sab => {
console.log('等待唤醒,或20秒后超时');
let result = Atomics.wait(new Int32Array(sab), 0, 0, 20000);
console.log('唤醒状态:', result);
flag = true;
});
setInterval(() => {
if (!flag) {
console.log('...', new Date);
}
}, 100);
}