-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathWorkerBees.js
89 lines (83 loc) · 2.14 KB
/
WorkerBees.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
import workerThreads from "worker_threads";
export function spawnImpl(left, right, worker, options, cb) {
worker.resolve(function(err, res) {
if (err) {
return cb(left(err))();
}
var thread;
// Must be either an absolute path or a relative path (i.e. relative to the
// current working directory) starting with ./ or ../, if a filepath.
// https://nodejs.org/api/worker_threads.html#new-workerfilename-options
var importPath = res.filePath;
try {
thread = new workerThreads.Worker(importPath, {
workerData: options.workerData
});
thread.on('message', function(value) {
return options.onMessage(value)();
});
thread.on('error', function(err) {
return options.onError(err)();
});
thread.on('exit', function(code) {
return options.onExit(code)();
});
thread.on('online', function() {
cb(right(thread))();
});
} catch(e) {
cb(left(e))();
}
});
}
export function unsafeMakeImpl(params) {
return {
resolve: function(cb) {
cb(void 0, params);
},
spawn: function() {
throw new Error("Cannot spawn unsafe worker directly.");
}
};
}
export function mainImpl(ctor) {
return function() {
if (workerThreads.isMainThread) {
throw new Error("Worker running on main thread.");
}
ctor({
exit: function() {
process.exit();
},
receive: function(cb) {
return function() {
workerThreads.parentPort.on('message', function(value) {
cb(value)();
});
};
},
reply: function(value) {
return function() {
workerThreads.parentPort.postMessage(value);
};
},
threadId: workerThreads.threadId,
workerData: workerThreads.workerData
})();
};
}
export function postImpl(value, worker) {
worker.postMessage(value);
}
export function terminateImpl(left, right, worker, cb) {
worker.terminate()
.then(function() {
cb(right(void 0))();
})
.catch(function(err) {
cb(left(err))();
});
}
export function threadId(worker) {
return worker.threadId;
}