在 javascript 中处理 async 函数的资源争用,核心在于利用 async/await 的同步代码结构来显式管理执行流,从而避免竞态条件。具体做法是:对于共享资源的读写操作,使用互斥锁(mutex)或信号量(semaphore)等原语进行包裹;或者通过单线程特性,将并发任务串行化执行。这样能确保在同一时刻只有一个异步任务访问临界区,保证数据一致性。

如何为共享变量实现一个基础的异步互斥锁
要实现一个基础的异步互斥锁,需要创建一个包含状态标志和等待队列的对象。当第一个请求获取锁时,它直接获得权限并返回一个释放函数;后续请求则进入等待状态,直到前一个请求调用释放函数后,才唤醒下一个等待者。这种机制确保了同一时间只有一个 async 函数能执行受保护的代码块。

class Mutex {
constructor() {
this.isLocked = false;
this.queue = [];
}
async acquire() {
if (!this.isLocked) {
this.isLocked = true;
return () => {
this.isLocked = false;
if (this.queue.length > 0) {
const next = this.queue.shift();
next.resolve();
}
};
} else {
await new Promise(resolve => {
this.queue.push({ resolve });
});
this.isLocked = true;
return () => {
this.isLocked = false;
if (this.queue.length > 0) {
const next = this.queue.shift();
next.resolve();
}
};
}
}
}
// 使用示例
const mutex = new Mutex();
let sharedResource = 0;
async function updateResource(id) {
const release = await mutex.acquire();
try {
console.log(`Task ${id} started`);
// 模拟耗时操作
await new Promise(r => setTimeout(r, 100));
sharedResource += 1;
console.log(`Task ${id} finished, resource: ${sharedResource}`);
} finally {
release();
}
}
Promise.all([
updateResource(1),
updateResource(2),
updateResource(3)
]).then(() => {
console.log('Final resource:', sharedResource);
});
运行上述代码,预期输出显示三个任务依次执行,最终 sharedResource 的值为 3。如果没有互斥锁,由于 await 的存在,虽然它们不会同时修改内存,但在高并发场景下,若逻辑更复杂(如先读后写),仍可能产生竞态。此锁确保了 acquire 到 release 之间的代码段是原子性的。
如何使用 Promise 链式调用替代锁来处理简单竞争
对于简单的资源竞争,如果不希望引入复杂的锁对象,可以利用 Promise 的链式调用特性,将多个异步任务串联起来。这种方法本质上是将并行执行的 Promise.all 改为串行执行的 .then() 链。每个任务必须在前一个任务完全结束后才开始,从而天然避免了资源争用。这种方式适合任务之间有依赖关系,或者资源访问频率较低的场景。

let counter = 0;
function task(n) {
return new Promise((resolve) => {
setTimeout(() => {
counter += n;
console.log(`Task ${n} completed, counter is now ${counter}`);
resolve();
}, Math.random() * 100); // 随机延迟
});
}
// 串行执行
async function runSerially() {
await task(1);
await task(2);
await task(3);
console.log('Serial execution final counter:', counter);
}
runSerially();
这段代码展示了串行执行的结果。与并行执行不同,串行执行保证了 task(1) 完全结束(包括其内部的 setTimeout 回调)后,才会开始 task(2)。因此,counter 的值会按顺序累加,不会出现因并发导致的计数错误。虽然牺牲了性能,但实现了零争用的安全性。
当 async 函数内部发生异常时,锁的状态如何保持正确
在基于 async/await 的互斥锁实现中,如果受保护的代码块抛出异常,必须确保锁被正确释放,否则会导致死锁。最佳实践是使用 try...finally 结构。无论 try 块中的代码是否成功执行,finally 块都会执行,从而调用锁的释放函数。这保证了即使某个任务失败,其他等待的任务也能继续获取锁并执行,维持系统的稳定性。
async function riskyOperation(id) {
const release = await mutex.acquire();
try {
if (id === 2) throw new Error('Simulated failure');
sharedResource += id;
console.log(`Success for ${id}`);
} catch (error) {
console.error(`Error in task ${id}:`, error.message);
} finally {
release();
console.log(`Lock released for task ${id}`);
}
}
Promise.all([
riskyOperation(1),
riskyOperation(2),
riskyOperation(3)
]).then(() => {
console.log('All tasks done, final resource:', sharedResource);
});
运行此代码,尽管 riskyOperation(2) 抛出异常,但 finally 块依然执行,锁被释放。其他任务(如 riskyOperation(3))能够正常获取锁并完成执行。最终 sharedResource 的值为 4(1+3),系统未因异常而挂起。这验证了 try...finally 在资源管理中的关键作用。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











