๐งต Multi-Threading
JavaScript parallelism with Workers
Deno Workers Fibonacci Example
main.ts
const numbers = [50, 50, 50, 50, 50];
numbers.forEach((n) => {
const worker = new Worker(
new URL("./worker.ts", import.meta.url).href,
{
type: "module",
}
);
// 1a. send data to worker to start
worker.postMessage({ n });
// 2b. Receive completed work from worker
worker.onmessage = (e) => {
console.log(`Main Thread (n=${n}):`, e.data);
worker.terminate();
};
});
worker.ts
// @ts-nocheck no types available
function fibonacci(num) {
if (num <= 1) return num;
return fibonacci(num - 1) + fibonacci(num - 2);
}
// 1b. Receive initial work from main thread
self.onmessage = (e) => {
const { n } = e.data;
const result = fibonacci(n);
// 2a. Send the result back to the main thread
self.postMessage(result);
self.close();
};