Chapter 10: Working with Workers samples
This commit is contained in:
parent
575ab40a00
commit
52d632f0d2
32
Chapter10/worker-app/fibonacci-worker.js
Normal file
32
Chapter10/worker-app/fibonacci-worker.js
Normal 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));
|
||||
}
|
||||
14
Chapter10/worker-app/fibonacci.js
Normal file
14
Chapter10/worker-app/fibonacci.js
Normal 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("...");
|
||||
20
Chapter10/worker-app/hello-worker.js
Normal file
20
Chapter10/worker-app/hello-worker.js
Normal 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);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user