UNPKG

@maximai/maxim-js

Version:

Maxim AI JS SDK. Visit https://getmaxim.ai for more info.

66 lines 1.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Mutex = void 0; const semaphore_1 = require("./semaphore"); class Mutex { /** * Creates a new Mutex instance with a given key * @param key - Unique identifier for the mutex */ constructor(key) { // Create a semaphore with maxLocks = 1 to implement mutex behavior this.semaphore = semaphore_1.Semaphore.get(key, 1); } /** * Acquires the lock. If the lock is already held, waits until it's released * @returns Promise that resolves when the lock is acquired */ async lock() { await this.semaphore.acquire(); } /** * Releases the held lock */ release() { this.semaphore.release(); } /** * Gets or creates a Mutex instance for the given key * @param key - Unique identifier for the mutex * @returns Mutex instance */ static get(key) { if (!Mutex.mutexes.has(key)) { Mutex.mutexes.set(key, new Mutex(key)); } return Mutex.mutexes.get(key); } /** * Executes a critical section with automatic lock handling * @param key - Unique identifier for the mutex * @param criticalSection - Async function to execute within the mutex * @returns Promise that resolves with the result of the critical section */ static async withLock(key, criticalSection) { const mutex = Mutex.get(key); await mutex.lock(); try { return await criticalSection(); } finally { mutex.release(); } } async withLock(criticalSection) { await this.lock(); try { return await criticalSection(); } finally { this.release(); } } } exports.Mutex = Mutex; Mutex.mutexes = new Map(); //# sourceMappingURL=mutex.js.map