-
Notifications
You must be signed in to change notification settings - Fork 0
/
mp.js
55 lines (48 loc) · 1.48 KB
/
mp.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
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
let id = 0;
let callbacks = {};
module.exports.fork = (env) => {
let worker = cluster.fork(env);
worker.on('message', (message) => {
// console.log(`Master ${process.pid} message`, message);
if (message.id) {
callbacks[message.id](message.responseData);
}
});
return worker;
};
module.exports.send = (worker, data, callback) => {
id++;
callbacks[id] = callback;
worker.send({
id: id,
data: data,
});
};
module.exports.start = (worker, data, callback) => {
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
require('./main.js');
} else {
console.log(`Worker ${process.pid} started ${process.env.worker}`);
require('./workers/' + process.env.worker + '.js');
}
};
module.exports.on = (callback) => {
if (!cluster.isMaster) {
process.on('message', (message) => {
// console.log(`Worker ${process.pid} message`, message);
callback(message.data, (responseData) => {
// console.log(`Worker ${process.pid} response`, responseData);
process.send({
id: message.id,
responseData: responseData,
});
});
});
}
};