js实现锁
实现互斥锁(Mutex)
在JavaScript中实现锁机制可以通过Promise和异步控制实现。以下是一个基于Promise的互斥锁实现:
class Mutex {
constructor() {
this._locked = false;
this._queue = [];
}
lock() {
return new Promise((resolve) => {
if (!this._locked) {
this._locked = true;
resolve();
} else {
this._queue.push(resolve);
}
});
}
unlock() {
if (this._queue.length > 0) {
const nextResolve = this._queue.shift();
nextResolve();
} else {
this._locked = false;
}
}
}
使用示例:
const mutex = new Mutex();
async function criticalSection() {
await mutex.lock();
try {
// 临界区代码
} finally {
mutex.unlock();
}
}
读写锁实现
对于读写分离场景,可以实现读写锁:
class ReadWriteLock {
constructor() {
this._readers = 0;
this._writers = 0;
this._writeQueue = [];
this._readQueue = [];
}
async readLock() {
return new Promise((resolve) => {
if (this._writers === 0 && this._writeQueue.length === 0) {
this._readers++;
resolve();
} else {
this._readQueue.push(resolve);
}
});
}
async writeLock() {
return new Promise((resolve) => {
if (this._readers === 0 && this._writers === 0) {
this._writers++;
resolve();
} else {
this._writeQueue.push(resolve);
}
});
}
readUnlock() {
this._readers--;
if (this._readers === 0 && this._writeQueue.length > 0) {
const nextResolve = this._writeQueue.shift();
this._writers++;
nextResolve();
}
}
writeUnlock() {
this._writers--;
if (this._readQueue.length > 0) {
while (this._readQueue.length > 0) {
const nextResolve = this._readQueue.shift();
this._readers++;
nextResolve();
}
} else if (this._writeQueue.length > 0) {
const nextResolve = this._writeQueue.shift();
this._writers++;
nextResolve();
}
}
}
基于SharedArrayBuffer的原子锁
在支持SharedArrayBuffer的环境中,可以使用Atomics API实现真正的原子锁:
// 必须在跨上下文环境(如Web Worker)中才能使用
const lockBuffer = new SharedArrayBuffer(4);
const lock = new Int32Array(lockBuffer);
function acquireLock() {
while (true) {
// 尝试获取锁
const oldValue = Atomics.compareExchange(lock, 0, 0, 1);
if (oldValue === 0) {
return; // 成功获取锁
}
// 等待锁释放
Atomics.wait(lock, 0, 1);
}
}
function releaseLock() {
// 释放锁
Atomics.store(lock, 0, 0);
// 唤醒一个等待的线程
Atomics.notify(lock, 0, 1);
}
使用async-mutex库
对于生产环境,推荐使用成熟的第三方库如async-mutex:

import { Mutex } from 'async-mutex';
const mutex = new Mutex();
async function criticalSection() {
const release = await mutex.acquire();
try {
// 临界区代码
} finally {
release();
}
}
这些实现方法各有适用场景,互斥锁适合简单同步需求,读写锁适合读多写少场景,原子锁适合真正的多线程环境,而第三方库则提供了更完善的解决方案。






