Repository navigation
Expand file tree
/
Copy paththreadman_thread.js
More file actions
195 lines (177 loc) · 6.56 KB
/
Copy paththreadman_thread.js
File metadata and controls
195 lines (177 loc) · 6.56 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/* global WebAssembly */
export default function thread(self) {
const MAXMEM = 32767;
let instance;
let memory;
let terminationTimeout = 200; // milliseconds
let terminationTimer;
let wantToTerminate = false;
if (self) {
self.onmessage = function(e) {
let data;
if (e.data) {
data = e.data;
} else {
data = e;
}
try {
if (data[0].cmd === "INIT") {
init(data[0]).then(function() {
console.log("INIT DONE");
self.postMessage({status: "initialized"});
// Start idle timer only after init completes so it never
// fires during async WASM compilation.
scheduleTermination();
});
return; // skip the scheduleTermination() call at the bottom
} else if (data[0].cmd === "TERMINATE") {
terminate();
} else {
let terminateAfterTask = false;
if (data[data.length-1].cmd === "TERMINATE") {
terminateAfterTask = true;
data.pop();
}
const res = runTask(data);
let transfers = [];
for (let i=0; i<res.length; i++) {
if (res[i] instanceof Uint8Array) {
transfers.push(res[i].buffer);
}
}
self.postMessage(res, transfers);
if (terminateAfterTask) {
terminate();
}
}
} catch (err) {
// Catch any error and send it back to main thread
self.postMessage({error: err.message});
}
scheduleTermination();
};
}
async function init(data) {
let wasmModule;
if (data.code instanceof WebAssembly.Module) {
console.log("Using precompiled WebAssembly.Module");
wasmModule = data.code;
} else {
console.log("Compiling WebAssembly.Module");
const code = new Uint8Array(data.code);
wasmModule = await WebAssembly.compile(code);
}
memory = new WebAssembly.Memory({initial:data.init, maximum: MAXMEM});
console.log("Initialized thread with memory", memory.buffer.byteLength / 1024 / 1024, "MB");
instance = await WebAssembly.instantiate(wasmModule, {
env: {
"memory": memory
}
});
if (data.terminationTimeout) {
terminationTimeout = data.terminationTimeout;
}
}
function alloc(length) {
const u32 = new Uint32Array(memory.buffer, 0, 1);
while (u32[0] & 3) u32[0]++; // Return always aligned pointers
const res = u32[0];
u32[0] += length;
if (u32[0] + length > memory.buffer.byteLength) {
const currentPages = memory.buffer.byteLength / 0x10000;
let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1;
if (requiredPages>MAXMEM) requiredPages=MAXMEM;
memory.grow(requiredPages-currentPages);
console.log("Growing memory to", memory.buffer.byteLength / 1024 / 1024, "MB");
}
return res;
}
function allocBuffer(buffer) {
const p = alloc(buffer.byteLength);
setBuffer(p, buffer);
return p;
}
function getBuffer(pointer, length) {
return new Uint8Array(memory.buffer, pointer, length);
}
function setBuffer(pointer, buffer) {
const u8 = new Uint8Array(memory.buffer);
u8.set(new Uint8Array(buffer), pointer);
}
function runTask(task) {
clearTimeout(terminationTimer);
wantToTerminate = false;
if (task[0].cmd === "INIT") {
return init(task[0]);
}
const ctx = {
vars: [],
out: []
};
const u32a = new Uint32Array(memory.buffer, 0, 1);
const oldAlloc = u32a[0];
for (let i=0; i<task.length; i++) {
switch (task[i].cmd) {
case "ALLOCSET":
if (task[i].len / 1024 / 1024 > 25) {
console.log("tasks", task);
//console.trace();
}
ctx.vars[task[i].var] = allocBuffer(task[i].buff);
break;
case "ALLOC":
if (task[i].len / 1024 / 1024 > 25) {
console.log("tasks", task);
//console.trace();
}
ctx.vars[task[i].var] = alloc(task[i].len);
break;
case "SET":
setBuffer(ctx.vars[task[i].var], task[i].buff);
break;
case "CALL": {
const params = [];
for (let j=0; j<task[i].params.length; j++) {
const p = task[i].params[j];
if (typeof p.var !== "undefined") {
params.push(ctx.vars[p.var] + (p.offset || 0));
} else if (typeof p.val != "undefined") {
params.push(p.val);
}
}
instance.exports[task[i].fnName](...params);
break;
}
case "GET":
ctx.out[task[i].out] = getBuffer(ctx.vars[task[i].var], task[i].len).slice();
break;
default:
throw new Error("Invalid cmd");
}
}
const u32b = new Uint32Array(memory.buffer, 0, 1);
u32b[0] = oldAlloc;
return ctx.out;
}
function scheduleTermination() {
clearTimeout(terminationTimer);
if (terminationTimeout > 0) {
terminationTimer = setTimeout(() => {
// 2-phase termination: notify main thread first; close only after
// it acks with TERMINATE. This prevents the race where the main
// thread dispatches a task to a worker that has already closed.
wantToTerminate = true;
if (self) self.postMessage({status: "want_to_terminate"});
}, terminationTimeout);
}
}
function terminate() {
clearTimeout(terminationTimer);
if (self) {
console.log("TERMINATE");
self.postMessage({status: "terminated"});
self.close();
}
}
return runTask;
}