Skip to content

Commit feaad37

Browse files
committed
Change cluster example and rename
1 parent f33c1d7 commit feaad37

File tree

5 files changed

+61
-72
lines changed

5 files changed

+61
-72
lines changed

cluster/master.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'use strict';
2+
3+
const os = require('os');
4+
const cluster = require('cluster');
5+
6+
console.log('Started master:', process.pid);
7+
8+
const cpuCount = os.cpus().length;
9+
const workers = [];
10+
for (let i = 0; i < cpuCount; i++) {
11+
const worker = cluster.fork();
12+
console.log('Started worker:', worker.process.pid);
13+
workers.push(worker);
14+
}
15+
16+
const task = [2, 17, 3, 2, 5, 7, 15, 22, 1, 14, 15, 9, 0, 11];
17+
const results = [];
18+
19+
workers.forEach((worker) => {
20+
21+
worker.send({ task });
22+
23+
worker.on('exit', (code) => {
24+
console.log('Worker exited:', worker.process.pid, code);
25+
});
26+
27+
worker.on('message', (message) => {
28+
29+
console.log('Message from worker', worker.process.pid);
30+
console.log(JSON.stringify(message));
31+
32+
results.push(message.result);
33+
34+
if (results.length === cpuCount) {
35+
process.exit(0);
36+
}
37+
38+
});
39+
40+
setTimeout(() => process.exit(1), 5000);
41+
42+
});
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
const cluster = require('cluster');
44

55
if (cluster.isMaster) {
6-
require('./master.js')();
6+
require('./master.js');
77
} else {
8-
require('./worker.js')();
8+
require('./worker.js');
99
}

cluster/worker.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
'use strict';
2+
3+
const cluster = require('cluster');
4+
5+
console.log('Hello from worker', process.pid, cluster.worker.id);
6+
7+
const caltulations = x => x * 2;
8+
9+
process.on('message', (message) => {
10+
11+
console.log('Message to worker ', process.pid)
12+
console.log(JSON.stringify(message));
13+
14+
const result = message.task.map(caltulations);
15+
process.send({ result });
16+
17+
});

workers/master.js

Lines changed: 0 additions & 43 deletions
This file was deleted.

workers/worker.js

Lines changed: 0 additions & 27 deletions
This file was deleted.

0 commit comments

Comments
 (0)