Skip to content

Commit 9b6552a

Browse files
committed
worker_threads_test.js
1 parent cfcee88 commit 9b6552a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#!/usr/bin/env node
2+
// Based on: https://medium.com/@Trott/using-worker-threads-in-node-js-80494136dbb6
3+
'use strict';
4+
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
5+
const min = 2;
6+
let primes = [];
7+
function generatePrimes(start, range) {
8+
console.log('started: ' + start);
9+
let isPrime = true;
10+
let end = start + range;
11+
for (let i = start; i < end; i++) {
12+
for (let j = min; j < Math.sqrt(end); j++) {
13+
if (i !== j && i%j === 0) {
14+
isPrime = false;
15+
break;
16+
}
17+
}
18+
if (isPrime) {
19+
primes.push(i);
20+
}
21+
isPrime = true;
22+
}
23+
console.log('ended: ' + start);
24+
}
25+
if (isMainThread) {
26+
const max = 1e2;
27+
const threadCount = +process.argv[2] || 10;
28+
const threads = new Set();;
29+
const range = Math.ceil((max - min) / threadCount);
30+
let start = min;
31+
for (let i = 0; i < threadCount - 1; i++) {
32+
const myStart = start;
33+
threads.add(new Worker(__filename, { workerData: { start: myStart, range }}));
34+
start += range;
35+
}
36+
threads.add(new Worker(__filename, { workerData: { start, range: range + ((max - min + 1) % threadCount)}}));
37+
for (let worker of threads) {
38+
worker.on('error', (err) => { throw err; });
39+
worker.on('exit', () => {
40+
threads.delete(worker);
41+
if (threads.size === 0) {
42+
console.log(primes.sort((a, b) => a - b).join('\n'));
43+
}
44+
})
45+
worker.on('message', (msg) => {
46+
primes = primes.concat(msg);
47+
});
48+
}
49+
} else {
50+
generatePrimes(workerData.start, workerData.range);
51+
parentPort.postMessage(primes);
52+
}

0 commit comments

Comments
 (0)