OpenWebProject Workers
Multithreaded worker pool
Installation
npm install owp.workers --save
Usage
; //Create new workers instance. Ie a new worker pool. //Pool size defaults to number of logical cores.const workers = ; //OR manually specify pool size.const workers = 4;
Add new work
Format
workers.add(file:string||constructor, message:any, transfer:array) => Promise
Example echo
- Runs worker in file
"workerEcho.js"
.- File parameter can be the workers file name or the constructor for the worker.
- Import constructor and then pass is used with webpack.
- Passes message
"Hello World"
to worker.- Message could be any data you want to pass not just a string.
- Message is optional.
workers "Hello world"
Example sum
- The buffer in TypedArrays like Int32Array cant be transfered to the worker thread using pass by reference instead of value, but the reference is remove from the original/calling thread.
const list = 3;list0 = 25;list1 = 666;list2 = 19; workers 710
Worker js format
onmessage(event)
callback is triggered when worker starts. This contains anevent.data
field to get message.- Worker calls
postMessage(data)
to give result and terminate worker.
workerEcho.js
{ ;};
workerSum.js
{ const list = edata; let sum = 0; for let i = 0; i < listlength; ++i sum += listi; ;};