-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThread.js
More file actions
48 lines (42 loc) · 1.05 KB
/
Thread.js
File metadata and controls
48 lines (42 loc) · 1.05 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
const { Worker, isMainThread, threadId, parentPort, workerData } = require('worker_threads');
class Thread {
constructor(argv) {
try {
this.argv = argv;
this.argv.run = argv.run.toString();
} catch (e) {
throw e;
}
if (!this.argv.num) {
throw new Error("Invalid argument");
}
}
start() {
if (isMainThread) {
return this.run = new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: {...this.argv}
});
worker.on("message", resolve);
worker.on("error", reject);
worker.on("exit", code => {
if (code !== 0) {
reject(new Error("worker stopped with exit code "+code));
}
});
});
} else {
function Runnable() {}
Runnable.prototype = this.argv;
Runnable.prototype._run = function() {
return eval(workerData.run).call(this);
};
var runnable = new Runnable();
runnable._run.call(runnable);
}
}
}
if (!isMainThread) {
new Thread(workerData).start();
}
module.exports = Thread;