Chapter 10: Working with Workers samples
This commit is contained in:
@@ -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));
|
||||||
|
}
|
||||||
@@ -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("...");
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user