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.
constsema = newSemaphore(3); // Allows up to 3 concurrent operations.
Properties
available
available:number
The number of available permits.
可用许可的数量。
capacity
capacity:number
The maximum number of concurrent operations allowed.
允许的最大并发操作数。
Methods
acquire
acquire():Promise<void>
Acquires a semaphore, blocking if necessary until one is available.
获取一个信号量,必要时阻塞直到有一个可用。
Returns Promise<void>
Example
constsema = newSemaphore(1);
asyncfunctioncriticalSection() { awaitsema.acquire(); try { // This code section cannot be executed simultaneously } finally { sema.release(); } }
release
release():void
Releases a semaphore, allowing one more operation to proceed.
释放一个信号量,允许另一个操作继续进行。
Returns void
Example
constsema = newSemaphore(1);
asyncfunctiontask() { awaitsema.acquire(); try { // This code can only be executed by two tasks at the same time } finally { sema.release(); // Allows another waiting task to proceed. } }
A counting semaphore for async functions that manages available permits. Semaphores are mainly used to limit the number of concurrent async tasks.
Each
acquireoperation takes a permit or waits until one is available. Eachreleaseoperation 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(先进先出)顺序来确保公平性。
Example