Skip to main content
Module

x/async/semaphore.ts>Semaphore

🦕 Asynchronous primitive modules loosely port from Python's asyncio for Deno.
Go to Latest
class Semaphore
import { Semaphore } from "https://deno.land/x/async@v1.1.2/semaphore.ts";

A Semaphore object. Not thread-safe.

A semaphore managers an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some task calls release().

The optinal value argument gives the initial value for the internal counter (1 by default). If the given value is less than 0 an Error is thrown.

The preferred way to use a Semaphore is with() method.

Constructors

new
Semaphore(value?)

Properties

protected
value: number

Methods

acquire(): Promise<true>

Acquire a semaphore.

If the internal counter is greater than zero, decrement it by one and return true immediately. If it is zero, wait until a release() is called and return true.

locked(): boolean

Return true if semaphore can not be acquired immediately.

release(): void

Release a semaphore, incrementing the internal counter by one. Can wak up a task waiting to acquire the semaphore.

Unlike BoundedSemaphore, Semaphore allows making more release() calls than acquire() calls.

with(callback: () => void | Promise<void>): Promise<void>

Acuire the lock and execute callback to access shared state.

This is preferred way to use a Semaphore.