Created
January 7, 2019 06:36
-
-
Save Trott/7bb7ee55c247047d030b4c427434ef51 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads'); | |
const min = 2; | |
let primes = []; | |
function generatePrimes(start, range) { | |
let isPrime = true; | |
let end = start + range; | |
for (let i = start; i < end; i++) { | |
for (let j = min; j < Math.sqrt(end); j++) { | |
if (i !== j && i%j === 0) { | |
isPrime = false; | |
break; | |
} | |
} | |
if (isPrime) { | |
primes.push(i); | |
} | |
isPrime = true; | |
} | |
} | |
if (isMainThread) { | |
const max = 1e7; | |
const threadCount = +process.argv[2] || 2; | |
const threads = new Set();; | |
console.log(`Running with ${threadCount} threads...`); | |
const range = Math.ceil((max - min) / threadCount); | |
let start = min; | |
for (let i = 0; i < threadCount - 1; i++) { | |
const myStart = start; | |
threads.add(new Worker(__filename, { workerData: { start: myStart, range }})); | |
start += range; | |
} | |
threads.add(new Worker(__filename, { workerData: { start, range: range + ((max - min + 1) % threadCount)}})); | |
for (let worker of threads) { | |
worker.on('error', (err) => { throw err; }); | |
worker.on('exit', () => { | |
threads.delete(worker); | |
console.log(`Thread exiting, ${threads.size} running...`); | |
if (threads.size === 0) { | |
console.log(primes.join('\n')); | |
} | |
}) | |
worker.on('message', (msg) => { | |
primes = primes.concat(msg); | |
}); | |
} | |
} else { | |
generatePrimes(workerData.start, workerData.range); | |
parentPort.postMessage(primes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Trott while reading your great article on medium, I stumbled upon a possible typo - Line 24:
const threads = new Set();;
- looks like redundant semicolon here