diff --git a/js/serialize/xserializer-pool.js b/js/serialize/xserializer-pool.js index 0603d14..6f22316 100644 --- a/js/serialize/xserializer-pool.js +++ b/js/serialize/xserializer-pool.js @@ -4,9 +4,17 @@ import genWorker from "/js/common/worker.js"; // Number const maxNumWorkers = Math.max(1, navigator.hardwareConcurrency); -// Array[{ isIdle: Boolean, worker: WebWorker }] +// type Job = { parcel: Object[Any], isHost: Boolean +// , post: MessagePort, type: String) } + +// type WorkerBundle = { isIdle: Boolean, worker: WebWorker } + +// Array[WorkerBundle] const workerPool = []; +// Array[Job] +const jobQueue = []; + // (String, String) => Unit const initWorker = (workerPath, msgType) => { const worker = genWorker(workerPath); @@ -22,22 +30,35 @@ const xserialize = (parcel, isHost, port, type) => { (bundle) => bundle.isIdle && bundle.worker.messageType === type ); + const job = { parcel, isHost, port, type }; + if (workerBundle !== undefined) { + runWorker(job, workerBundle); + } else { + jobQueue.push(job); + } + +}; - workerBundle.isIdle = false; +// ({ Object[Any], Boolean, MessagePort, String }, WorkerBundle) => Unit +const runWorker = ({ parcel, isHost, port, type }, workerBundle) => { - const message = { parcel, isHost }; + workerBundle.isIdle = false; - awaitWorker(workerBundle.worker)(type, message).then( - (xserialized) => { + const message = { parcel, isHost }; + + awaitWorker(workerBundle.worker)(type, message).then( + (xserialized) => { + + port.postMessage(xserialized); + + if (jobQueue.length > 0) { + runWorker(jobQueue.shift(), workerBundle); + } else { workerBundle.isIdle = true; - port.postMessage(xserialized); } - ); - - } else { - setTimeout((() => xserialize(parcel, isHost, port, type)), 1); - } + } + ); };