1 |
|
2 | var Semaphore = (function () {
|
3 | function Semaphore(n) {
|
4 | this.n = n;
|
5 | this._queued = [];
|
6 | this._avail = n;
|
7 | }
|
8 | Semaphore.prototype.enter = function (fn) {
|
9 | if (this._avail > 0) {
|
10 | --this._avail;
|
11 | fn();
|
12 | }
|
13 | else {
|
14 | this._queued.push(fn);
|
15 | }
|
16 | };
|
17 | Semaphore.prototype.leave = function () {
|
18 | if (this._queued.length > 0) {
|
19 | var fn = this._queued.pop();
|
20 | fn();
|
21 | }
|
22 | else {
|
23 | ++this._avail;
|
24 | }
|
25 | };
|
26 | Semaphore.unlimited = new Semaphore(10000000);
|
27 | return Semaphore;
|
28 | })();
|
29 | module.exports = Semaphore;
|
30 |
|
\ | No newline at end of file |