Skip to main content

Home > flowp > Semaphore

Semaphore class

Semaphore with async api

Signature:

export declare class Semaphore 

Example

const sem = new Semaphore(5) const release = await sem.acquire() // do something release()

Constructors

ConstructorModifiersDescription
(constructor)(permits)constructs a new Semaphore with n permits

Properties

PropertyModifiersTypeDescription
frozen?Future<void>(Optional) check if semaphore is frozen (non-undefined value), other uses are not guaranteed
isEmptyboolean

Check if no task is using the semaphore'

always return true if permits = 0

isFullboolean

Check if all permits are being used

always return true if permits = 0

permitsnumberGet the number of total permits currently
remainnumberGet the number of remaining permits

Methods

MethodModifiersDescription
acquire(timeout)Acquire a permit, resolve when resouce is available.
freeze()

Freeze this semaphore, calling acquire won't resolve and tryAcquire will throw (release can still be called).

NOTE: don't call this again if Semaphore.frozen, not supported yet

grant(permits)Give n permits to the semaphore, will immediately start this number of waiting tasks if not frozen
revoke(permits)

Destroy n permits, effective until remain fills the n permits

**note**: you may need to check if permits > semaphore.permits, or it will wait until granted that many permits

schedule(fn)Schedule a task to run when a permit is available and automatically release after run.
tryAcquire()Try to synchronosly acquire if there's remaining permits
unfreeze()unfreeze this semaphore, it is synchronos and the returned value should be ignored