UNPKG

nanolith

Version:

Multi-threading in no time with seamless TypeScript support.

1 lines 1.49 kB
import{Worker,SHARE_ENV}from"worker_threads";import{generateConcurrencyValue,getConcurrencyCounter,getActiveCounter}from"./utilities.js";import{ConcurrencyOption}from"../constants/pool.js";import{PoolItem}from"./pool_item.js";import{SharedCounter,SharedU32Integer}from"../utilities/index.js";export const pool=Object.seal(new class{#e=getConcurrencyCounter();#t=getActiveCounter();#r=[];option=ConcurrencyOption;get maxConcurrency(){return SharedU32Integer.getValue(this.#e)}get maxed(){return SharedCounter.getCount(this.#t)>=SharedU32Integer.getValue(this.#e)}get queueLength(){return this.#r.length}get activeCount(){return SharedCounter.getCount(this.#t)}get idle(){return!SharedCounter.getCount(this.#t)}get next(){return this.#r[0].options}setConcurrency(e){if(!Object.values(ConcurrencyOption).includes(e))throw new Error(`${e} is not a valid and safe ConcurrencyOption!`);SharedU32Integer.setValue(this.#e,(()=>generateConcurrencyValue(e)))}__enqueue(e){if(!(e instanceof PoolItem))throw new Error("The provided item cannot be enqueued.");e.options.priority?this.#r.unshift(e):this.#r.push(e),this.maxed||this.#n()}#n(){if(this.maxed||!this.#r.length)return;SharedCounter.incr(this.#t);const e=this.#r.shift(),{file:t,workerData:r,options:n,reffed:o,shareEnv:i}=e.options,u=new Worker(t,{...n,workerData:{...r,pool:{active:this.#t,concurrency:this.#e}},env:i?SHARE_ENV:void 0});o?u.ref():u.unref(),e.emit("created",u),u.once("exit",(()=>{SharedCounter.decr(this.#t),this.#n()}))}});