|
Last change
on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago |
|
Fix frontend appearance
|
-
Property mode
set to
100644
|
|
File size:
1.4 KB
|
| Line | |
|---|
| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Tobias Koppers @sokra
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | "use strict";
|
|---|
| 7 |
|
|---|
| 8 | /**
|
|---|
| 9 | * Simple counting semaphore used to limit how many asynchronous tasks may run
|
|---|
| 10 | * concurrently.
|
|---|
| 11 | */
|
|---|
| 12 | class Semaphore {
|
|---|
| 13 | /**
|
|---|
| 14 | * Initializes the semaphore with the number of permits that may be held at
|
|---|
| 15 | * the same time.
|
|---|
| 16 | * @param {number} available the amount available number of "tasks"
|
|---|
| 17 | * in the Semaphore
|
|---|
| 18 | */
|
|---|
| 19 | constructor(available) {
|
|---|
| 20 | this.available = available;
|
|---|
| 21 | /** @type {(() => void)[]} */
|
|---|
| 22 | this.waiters = [];
|
|---|
| 23 | /** @private */
|
|---|
| 24 | this._continue = this._continue.bind(this);
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | /**
|
|---|
| 28 | * Acquires a permit for the callback immediately when one is available or
|
|---|
| 29 | * queues the callback until another task releases its permit.
|
|---|
| 30 | * @param {() => void} callback function block to capture and run
|
|---|
| 31 | * @returns {void}
|
|---|
| 32 | */
|
|---|
| 33 | acquire(callback) {
|
|---|
| 34 | if (this.available > 0) {
|
|---|
| 35 | this.available--;
|
|---|
| 36 | callback();
|
|---|
| 37 | } else {
|
|---|
| 38 | this.waiters.push(callback);
|
|---|
| 39 | }
|
|---|
| 40 | }
|
|---|
| 41 |
|
|---|
| 42 | /**
|
|---|
| 43 | * Releases a permit and schedules the next waiting callback, if any.
|
|---|
| 44 | */
|
|---|
| 45 | release() {
|
|---|
| 46 | this.available++;
|
|---|
| 47 | if (this.waiters.length > 0) {
|
|---|
| 48 | process.nextTick(this._continue);
|
|---|
| 49 | }
|
|---|
| 50 | }
|
|---|
| 51 |
|
|---|
| 52 | /**
|
|---|
| 53 | * Drains the next waiting callback after a permit becomes available.
|
|---|
| 54 | */
|
|---|
| 55 | _continue() {
|
|---|
| 56 | if (this.available > 0 && this.waiters.length > 0) {
|
|---|
| 57 | this.available--;
|
|---|
| 58 | const callback = /** @type {(() => void)} */ (this.waiters.pop());
|
|---|
| 59 | callback();
|
|---|
| 60 | }
|
|---|
| 61 | }
|
|---|
| 62 | }
|
|---|
| 63 |
|
|---|
| 64 | module.exports = Semaphore;
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.