@pengzhanbo/utils - v3.12.0
    Preparing search index...

    Class Semaphore

    A counting semaphore for async functions that manages available permits. Semaphores are mainly used to limit the number of concurrent async tasks.

    Each acquire operation takes a permit or waits until one is available. Each release operation adds a permit, potentially allowing a waiting task to proceed.

    The semaphore ensures fairness by maintaining a FIFO (First In, First Out) order for acquirers.

    异步函数使用的计数信号量,管理可用许可。 信号量主要用于限制并发异步任务的数量。

    每次 acquire 操作都会获取一个许可,或者等待直到有一个许可可用。 每次 release 操作都会增加一个许可,可能允许等待的任务继续执行。

    信号量通过维护获取者的 FIFO(先进先出)顺序来确保公平性。

    const sema = new Semaphore(2);

    async function task() {
    await sema.acquire();
    try {
    // This code can only be executed by two tasks at the same time
    } finally {
    sema.release();
    }
    }

    task();
    task();
    task(); // This task will wait until one of the previous tasks releases the semaphore.
    Index
    • Creates an instance of Semaphore.

      创建一个信号量实例。

      Parameters

      • capacity: number

        允许的最大并发操作数。

      Returns Semaphore

      如果 capacity 不是正整数。

      const sema = new Semaphore(3); // Allows up to 3 concurrent operations.
      
    capacity: number

    The maximum number of concurrent operations allowed.

    允许的最大并发操作数。

    • Acquires a semaphore, blocking if necessary until one is available.

      获取一个信号量,必要时阻塞直到有一个可用。

      Returns Promise<void>

      const sema = new Semaphore(1);

      async function criticalSection() {
      await sema.acquire();
      try {
      // This code section cannot be executed simultaneously
      } finally {
      sema.release();
      }
      }
    • Releases a semaphore, allowing one more operation to proceed.

      释放一个信号量,允许另一个操作继续进行。

      Returns void

      const sema = new Semaphore(1);

      async function task() {
      await sema.acquire();
      try {
      // This code can only be executed by two tasks at the same time
      } finally {
      sema.release(); // Allows another waiting task to proceed.
      }
      }
    • Tries to acquire a permit without waiting.

      尝试立即获取一个许可,不等待。

      Returns (() => void) | undefined

      A function that releases the acquired permit, or undefined when no permit is available (in which case the caller should fall back to acquire). 获取成功时返回释放许可的函数;无可用许可时返回 undefined(调用方应回退到 acquire)。

      Unlike acquire, this method never queues and never allocates a Promise. 与 acquire 不同,此方法不会排队,也不会分配 Promise。

      const release = semaphore.tryAcquire()
      if (release) {
      try { ... } finally { release() }
      }