-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulate.js
61 lines (53 loc) · 1.49 KB
/
simulate.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const Maximizer = require('./concurrency-maximizer');
const Promise = require('bluebird');
function work(counter) {
return Promise.resolve().then(() => {
var value = Math.random() * 100000;
for (var i = 1; i < 10000; i++) {
value /= i;
}
if (counter > 0) return Promise.delay(1).then(() => work(counter - 1));
return value;
});
}
class Worker {
constructor(taskSize, numberToRun) {
this.maximizer = new Maximizer(15, 0.5, 200, 2);
this.numberActive = 0;
this.numberToRun = numberToRun;
this.taskSize = taskSize;
this.checkShouldRun();
}
checkShouldRun() {
if (this.numberToRun-- <= 0) {
if (!this.loggedMessage) {
this.maximizer = null;
this.loggedMessage = true;
console.log("Finished worker");
}
return;
}
if (this.numberActive < this.maximizer.concurrency) {
this.runOne();
this.checkShouldRun();
}
}
runOne() {
let finishToken = this.maximizer.startItem();
this.numberActive++;
work(10 * this.taskSize).then(() => {
finishToken();
this.numberActive--;
this.checkShouldRun();
});
}
}
let workers = [];
function createWorker() {
workers.push(new Worker(Math.floor(Math.random()*3)+2, 80000 + Math.floor(Math.random() * 80000)));
setTimeout(createWorker, 30000 + (2500 * workers.length * workers.length));
}
createWorker();
setInterval(() => {
console.log(workers.map(worker => worker.maximizer && worker.maximizer.concurrency).join('\t'));
}, 100);