Skip to main content

Built and signed on GitHub Actions

A modern JavaScript utility library that's 2-3 times faster and up to 97% smaller—a major upgrade to lodash.

This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score
100%
Published
2 weeks ago (1.32.0)
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.

Examples

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.

Constructors

new
Semaphore(capacity: number)

Creates an instance of Semaphore.

Properties

The number of available permits.

The maximum number of concurrent operations allowed.

private
deferredTasks: Array<() => void>

Methods

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

release(): void

Releases a semaphore, allowing one more operation to proceed.

Add Package

deno add jsr:@es-toolkit/es-toolkit

Import symbol

import { Semaphore } from "@es-toolkit/es-toolkit/compat";

---- OR ----

Import directly with a jsr specifier

import { Semaphore } from "jsr:@es-toolkit/es-toolkit/compat";

Add Package

npx jsr add @es-toolkit/es-toolkit

Import symbol

import { Semaphore } from "@es-toolkit/es-toolkit/compat";

Add Package

yarn dlx jsr add @es-toolkit/es-toolkit

Import symbol

import { Semaphore } from "@es-toolkit/es-toolkit/compat";

Add Package

pnpm dlx jsr add @es-toolkit/es-toolkit

Import symbol

import { Semaphore } from "@es-toolkit/es-toolkit/compat";

Add Package

bunx jsr add @es-toolkit/es-toolkit

Import symbol

import { Semaphore } from "@es-toolkit/es-toolkit/compat";