X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FAsyncLock.ts;h=9c0584565e3ecb80897b2ad32418a1afdb0cc888;hb=d929adcc32a8cc79f0c7182d16f70367b001d28c;hp=7f44bd257251f32cde860ce6a40d6eb82cf1a51c;hpb=dd485b567f2f1b595c8241fa2cf74ba0c27911f0;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/AsyncLock.ts b/src/utils/AsyncLock.ts index 7f44bd25..9c058456 100644 --- a/src/utils/AsyncLock.ts +++ b/src/utils/AsyncLock.ts @@ -1,39 +1,43 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. +import Queue from 'mnemonist/queue.js'; + export enum AsyncLockType { configuration = 'configuration', performance = 'performance', } +type ResolveType = (value: void | PromiseLike) => void; + export class AsyncLock { private static readonly asyncLocks = new Map(); private acquired: boolean; - private readonly resolveQueue: ((value: void | PromiseLike) => void)[]; + private readonly resolveQueue: Queue; - private constructor(private readonly type: AsyncLockType) { + private constructor() { this.acquired = false; - this.resolveQueue = []; + this.resolveQueue = new Queue(); } public static async acquire(type: AsyncLockType): Promise { const asyncLock = AsyncLock.getAsyncLock(type); if (!asyncLock.acquired) { asyncLock.acquired = true; - } else { - return new Promise((resolve) => { - asyncLock.resolveQueue.push(resolve); - }); + return; } + return new Promise((resolve) => { + asyncLock.resolveQueue.enqueue(resolve); + }); } public static async release(type: AsyncLockType): Promise { const asyncLock = AsyncLock.getAsyncLock(type); - if (asyncLock.resolveQueue.length === 0 && asyncLock.acquired) { + if (asyncLock.resolveQueue.size === 0 && asyncLock.acquired) { asyncLock.acquired = false; return; } - const queuedResolve = asyncLock.resolveQueue.shift(); - return new Promise((resolve) => { + const queuedResolve = asyncLock.resolveQueue.dequeue()!; + return new Promise((resolve) => { queuedResolve(); resolve(); }); @@ -41,8 +45,8 @@ export class AsyncLock { private static getAsyncLock(type: AsyncLockType): AsyncLock { if (!AsyncLock.asyncLocks.has(type)) { - AsyncLock.asyncLocks.set(type, new AsyncLock(type)); + AsyncLock.asyncLocks.set(type, new AsyncLock()); } - return AsyncLock.asyncLocks.get(type); + return AsyncLock.asyncLocks.get(type)!; } }