Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Calculating prime numbers on serverless platforms using Node.js Worker Threads and IBM Cloud Functions (Apache OpenWhisk)
'use strict';
const { Worker } = require('worker_threads');
const os = require('os')
const threadCount = os.cpus().length
const compute_primes = async (start, range) => {
return new Promise((resolve, reject) => {
let primes = []
console.log(`adding worker (${start} => ${start + range})`)
const worker = new Worker('./worker.js', { workerData: { start, range }})
worker.on('error', reject)
worker.on('exit', () => resolve(primes))
worker.on('message', msg => {
primes = primes.concat(msg)
})
})
}
async function main(params) {
const { min, max } = params
const range = Math.ceil((max - min) / threadCount)
let start = min < 2 ? 2 : min
const workers = []
console.log(`Calculating primes with ${threadCount} threads...`);
for (let i = 0; i < threadCount - 1; i++) {
const myStart = start
workers.push(compute_primes(myStart, range))
start += range
}
workers.push(compute_primes(start, max - start))
const primes = await Promise.all(workers)
return { primes: primes.flat() }
}
exports.main = main
'use strict';
const min = 2
function main(params) {
const { start, end } = params
console.log(params)
const primes = []
let isPrime = true;
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;
}
return { primes }
}
'use strict';
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const min = 2
function generatePrimes(start, range) {
const primes = []
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;
}
return primes
}
const primes = 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
You can’t perform that action at this time.