Skip to content

Commit

Permalink
Perf/Bugfix: Use queue for better message ordering
Browse files Browse the repository at this point in the history
Rather than thrashing around with `setTimeout`
  • Loading branch information
TheBizzle committed Oct 29, 2023
1 parent d8f5989 commit c0894a4
Showing 1 changed file with 32 additions and 11 deletions.
43 changes: 32 additions & 11 deletions js/serialize/xserializer-pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
}
}
);

};

Expand Down

0 comments on commit c0894a4

Please sign in to comment.