const { spawn, Pool, Thread, Worker, } = require('threads'); const { cpus } = require('node:os'); /** * Use a thread pool of a fixed size * @param {number} size number of threads * @param {string} name name of file in workers directory * @param {function} fun async function * @returns {Promise} */ async function pool(size, name, fun) { const pool = Pool(() => spawn(new Worker(`./workers/${name}.js`)), { size }); try { return await fun(pool); } finally { pool.settled().then(() => pool.terminate()); } }; /** * Spawn one thread, do something, and terminate it * @param {string} name name of file in workers directory * @param {function} fun async function * @returns {Promise} */ function relativePool(fraction, ...args) { // ! ceiL: at least 1 const poolSize = Math.ceil(fraction * cpus().length); return pool(poolSize, ...args); } module.exports = { pool, quick, relativePool, };