Skip to content

Instantly share code, notes, and snippets.

@sirisian
Created January 26, 2023 06:08
Show Gist options
  • Save sirisian/df6666349b1fd4eaf831834169052c6f to your computer and use it in GitHub Desktop.
Save sirisian/df6666349b1fd4eaf831834169052c6f to your computer and use it in GitHub Desktop.
web worker examples
async function SingleWorkerExample(data, param1, param2) {
return new Promise(resolve => {
const blobURL = URL.createObjectURL(new Blob(['(', function() {
onmessage = e => {
const { data, param1, param2 } = e.data;
// Do work with data which is a SharedArrayBuffer
postMessage('done');
};
}.toString(), ')()'], { type: 'application/javascript' }));
const worker = new Worker(blobURL);
URL.revokeObjectURL(blobURL);
worker.postMessage({ data, param1, param2 });
worker.onmessage = e => {
worker.terminate();
resolve();
};
});
}
 
function ExternalFunction() {}
 
async function MultiWorkerExample(threadCount, data, param1, param2) {
const blobURL = URL.createObjectURL(new Blob([ExternalFunction.toString(), '(', function() {
onmessage = e => {
const { workerIndex, threadCount, data, param1, param2 } = e.data;
// Use workerIndex to divide work by threadCount
// Can call ExternalFunction that is included
postMessage('done');
};
}.toString(), ')()'], { type: 'application/javascript' }));
const workers = [];
for (let workerIndex = 0; workerIndex < threadCount; ++workerIndex) {
workers.push(new Promise(resolve => {
const worker = new Worker(blobURL);
worker.postMessage({ workerIndex, threadCount, data, param1, param2 }); // Starts the computation
worker.onmessage = e => {
worker.terminate();
resolve();
};
}));
}
await Promise.all(workers);
URL.revokeObjectURL(blobURL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment