Chapter 10: Working with Workers samples

This commit is contained in:
Beth Griggs 2020-08-31 01:12:46 +01:00
parent 575ab40a00
commit 52d632f0d2
No known key found for this signature in database
GPG Key ID: D7062848A1AB005C
3 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,32 @@
const {
Worker,
isMainThread,
parentPort,
workerData,
} = require("worker_threads");
const n = 10;
// Fibonacci calculator
const fibonacci = (n) => {
let a = 0, b = 1, next = 1, i = 2;
for (i; i <= n; i++) {
next = a + b;
a = b;
b = next;
}
return next;
};
if (isMainThread) {
// Main thread code
const worker = new Worker(__filename, {
workerData: n,
});
worker.on("message", (msg) => {
console.log(`The Fibonacci number at position ${n} is ${msg}`);
});
console.log("...");
} else {
// Worker code
parentPort.postMessage(fibonacci(workerData));
}

View File

@ -0,0 +1,14 @@
const n = 10;
// Fibonacci calculator
const fibonacci = (n) => {
let a = 0, b = 1, next = 1, i = 2;
for (i; i <= n; i++) {
next = a + b;
a = b;
b = next;
}
console.log(`The Fibonacci number at position ${n} is ${next}`);
};
fibonacci(n);
console.log("...");

View File

@ -0,0 +1,20 @@
const {
Worker,
isMainThread,
parentPort,
workerData,
} = require("worker_threads");
if (isMainThread) {
// Main thread code
const worker = new Worker(__filename, {
workerData: "Beth",
});
worker.on("message", (msg) => {
console.log(msg);
});
} else {
// Worker code
const greeting = `Hello ${workerData}!`;
parentPort.postMessage(greeting);
}