Skip to main content

Basic Worker

This example demonstrates how to use the WorkerPool in a Node.js environment to execute CPU-intensive math operations concurrently.

import { WorkerPool, StatusType } from '@renderdev/threadpool/node'

const startTime = performance.now()

const pool = (new WorkerPool(new URL('./worker-file.js', import.meta.url)))
.race((data, thread) => {
console.log(`Finished First: ${thread.meta} = ${data}\n`)
})
.then((data, thread) => {
console.log(`*`, thread.meta, Array.isArray(data) ? data.length : data)
})
.allSettled(() => {
console.log(`\nDONE! Completed: ${pool.status('completed', StatusType.COUNT)} Tasks.`)
const endTime = performance.now()
const elapsedTime = endTime - startTime
console.log(`\n\nScript runtime: ${(Math.round(elapsedTime) / 1000)} sec\n`)
})

// Enable exit event fallback for runtimes that have not fully implemented the Node's `worker_threads`
await pool.enableExitEventFallback()

pool.addTask({ fn: 'fib', args: [42] }, 'fib(42)')
pool.addTask({ fn: 'findPrimesUpTo', args: [17000000] }, 'findPrimesUpTo(17000000)')
pool.addTask({ fn: 'tribonacci', args: [32] }, 'tribonacci(32)')
pool.addTask({ fn: 'estimatePi', args: [25] }, 'estimatePi(25)')
info

We import from @renderdev/threadpool/node but the global @renderdev/threadpool will also work. Throughout the documentation, you may see both the entry point specific import and the global import.