-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor.js
43 lines (35 loc) · 823 Bytes
/
monitor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* A simple monitor that acts as a counting semaphore for managing usage of a
* limited set of resources.
*/
exports.semaphore = function (num) {
// Private
var count = num,
waiting = [];
// Public
var public = {};
public.wait = function (fn) {
var args = Array.prototype.slice.call(arguments, 1, arguments.length);
if (count > 0) {
fn.apply(fn, args);
count -= 1;
}
else {
waiting.push({
function: fn,
arguments: args,
});
}
}
public.signal = function () {
if (waiting.length == 0) {
count += 1;
}
else {
var item = waiting.pop();
item.function.apply(item.function, item.arguments);
}
console.log("signal, remaining: %d; available: %d", waiting.length, count);
}
return public;
}