Created
January 26, 2023 06:08
-
-
Save sirisian/df6666349b1fd4eaf831834169052c6f to your computer and use it in GitHub Desktop.
web worker examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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