-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathmain.js
More file actions
35 lines (26 loc) · 920 Bytes
/
main.js
File metadata and controls
35 lines (26 loc) · 920 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
27
28
29
30
31
32
33
34
35
import { Worker } from 'node:worker_threads';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const performCalculations = async () => {
const numCPUs = os.cpus().length;
const results = [];
const workers = [];
for (let i = 0; i < numCPUs; i++) {
const worker = new Worker(path.resolve(__dirname, 'worker.js'));
workers.push(worker);
const n = 10 + i;
const promise = new Promise((resolve) => {
worker.once('message', (msg) => resolve(msg));
worker.once('error', () => resolve({ status: 'error', data: null }));
});
worker.postMessage(n);
results.push(promise);
}
const finalResults = await Promise.all(results);
console.log(finalResults);
workers.forEach((w) => w.terminate());
};
await performCalculations();