workerhelp
Version:
基于Node.js worker_threads 的轻量级跨线程RPC通信模块,支持主线程与Worker线程之间的异步方法调用。
37 lines (32 loc) • 1.02 kB
JavaScript
// 锁的状态:0=未锁定,1=锁定
const LOCKED = 1;
const UNLOCKED = 0;
// 自定义互斥锁类
class Mutex {
constructor(sharedBuffer) {
this.lockView = new Int32Array(sharedBuffer);
}
// 获取锁(阻塞直到成功)
lock() {
while (true) {
// 原子性检查锁状态:若为 UNLOCKED,则设置为 LOCKED
const status = Atomics.compareExchange(
this.lockView, 0, // 操作共享内存的第0个位置
UNLOCKED, LOCKED // 期望原值为 UNLOCKED,设置为 LOCKED
);
if (status === UNLOCKED) {
return; // 成功获取锁
}
// 锁被占用,等待锁释放(避免忙等待,释放CPU)
Atomics.wait(this.lockView, 0, LOCKED);
}
}
// 释放锁
unlock() {
// 将锁状态重置为 UNLOCKED
Atomics.store(this.lockView, 0, UNLOCKED);
// 通知所有等待的线程
Atomics.notify(this.lockView, 0, 1);
}
}
module.exports = { Mutex,LOCKED,UNLOCKED };