-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (76 loc) · 1.96 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'use strict';
class Scheduler {
constructor(sch) {
this.ready = [];
this.signals = {};
this.idle = true;
this.schedFunction = sch;
}
newThread(T) {
if ((!(T instanceof Thread)) && (T instanceof Function)) {
T = new Thread(T, this);
}
if (T instanceof Thread) {
T.scheduler = this;
this.ready.push(T);
if (this.idle) {
this.idle = false;
setTimeout(() => {this.start();}, 0);
}
return true;
}
return false;
}
trigger(sig) {
if(!this.signals[sig])return;
this.ready = this.ready.concat(this.signals[sig]);
delete this.signals[sig];
if(this.idle) {
this.idle = false;
setTimeout(() => {this.start();}, 0);
}
}
start() {
if (this.ready.length === 0) {
this.idle = true;
return;
}
var T = this.schedFunction(this.ready);
var yieldCall = T.runnable.next();
this.ready.splice(this.ready.indexOf(T), 1);
if(yieldCall.value) {
var sig = yieldCall.value;
if (!this.signals[sig]) this.signals[sig] = [];
this.signals[sig].push(T);
}
else if(!yieldCall.done) {
this.ready.push(T);
}
setTimeout(() => {this.start();}, 0);
}
static fcfs(ready) {
return ready[0];
}
static schedulers() {
return {
'fcfs': Scheduler.fcfs
};
}
}
var currentTid = 0;
class Thread {
constructor(gen, sch) {
this.tid = currentTid;
currentTid ++;
this.sched = sch;
this.runnable = gen(this);
}
}
var sched = new Scheduler(Scheduler.fcfs);
module.exports = (T) => {
sched.newThread(T);
};
module.exports.schedulers = Scheduler.schedulers();
module.exports.scheduleWith = (F) => {
sched.schedFunction = F;
};