docs: mutex.

This commit is contained in:
Ansolve 2024-01-12 20:57:00 +08:00
parent b552dbfd01
commit 0c50475296
No known key found for this signature in database
GPG Key ID: 2F2873AC9538CC2D
1 changed files with 18 additions and 1 deletions

View File

@ -1,18 +1,24 @@
/**
*
* 一个非常普通的
*/
export class Mutex {
/**
* 锁目前的状态只有unlockedlocked两种情况
*
* @type {'locked' | 'unlocked'}
*/
#status;
/**
* 上锁后用于等待的锁Promise
*
* @type {null | Promise<void>}
*/
#promise;
/**
* 上锁后用于触发锁Promise的resolve函数
*
* @type {null | function(): void}
*/
#resolve;
@ -23,6 +29,11 @@ export class Mutex {
this.#resolve = null;
}
/**
* 上锁
*
* 请时刻记住使用`await Mutex#lock()`来使锁正常工作
*/
async lock() {
switch (this.#status) {
case 'locked':
@ -36,6 +47,11 @@ export class Mutex {
}
}
/**
* 解锁
*
* 请不要在未上锁的情况下解锁
*/
unlock() {
if (this.#status === 'unlocked') throw new Error('This Mutex is not locked.');
@ -44,6 +60,7 @@ export class Mutex {
}
/**
* 启用锁的try-finally封装用于在函数执行完后自动解放锁的控制权就算发生错误
*
* @param {function(): void | Promise<void>} content
*/