-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclusters.js
More file actions
26 lines (25 loc) · 1009 Bytes
/
clusters.js
File metadata and controls
26 lines (25 loc) · 1009 Bytes
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
import cluster from 'cluster';
import os from 'os';
// import { workerData } from 'worker_threads';
//cpus returns an array of objects containing information about each logical CPU core.
const CPUS = os.cpus();
console.log(cluster.isPrimary); /// undefined
console.log(cluster.isMaster); /// true
if(cluster.isMaster){
//fork() Spawn(تخمریزی) a new worker process. This can only be called from the primary process.
CPUS.forEach(() => cluster.fork());
cluster.on('listening', worker => {
console.log('Cluster %d connected: ', worker.process.pid);
});
cluster.on('disconnect', worker => {
console.log('Cluster %d is disconnected', worker.process.pid);
})
cluster.on('exit', worker => {
console.log('Cluster %d is dead: ', worker.process.pid);
cluster.fork();
//Ensure to starts a new cluster if an old one dies
});
} else {
//started via "./index.js" for new child process.
require('./index.js');
}