Skip to content

Commit 293a22c

Browse files
committed
Add shared thread example
1 parent bd67e65 commit 293a22c

3 files changed

Lines changed: 29 additions & 4 deletions

File tree

src/workers/fibonacciWorker.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ const runFibonacci = workerData => {
1313
};
1414

1515
if (!isMainThread) {
16-
const number = fb.iterate(workerData.iterations);
17-
parentPort.postMessage({ number });
16+
const result = fb.iterate(workerData.iterations);
17+
parentPort.postMessage(result);
1818
}
1919

2020
module.exports = runFibonacci;

src/workers/fibonacciWorkerPool.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ const runFibonacci = workerData => {
1919
};
2020

2121
if (!isMainThread) {
22-
const number = fb.iterate(workerData.iterations);
23-
parentPort.postMessage({ number });
22+
const result = fb.iterate(workerData.iterations);
23+
parentPort.postMessage(result);
2424
}
2525

2626
module.exports = runFibonacci;
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const fb = require('fibonacci');
2+
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
3+
4+
const runFibonacci = workerData => {
5+
return new Promise((resolve, reject) => {
6+
const worker = new Worker(__filename, { workerData });
7+
worker.on('message', resolve);
8+
worker.on('error', reject);
9+
worker.on('exit', code => {
10+
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
11+
});
12+
});
13+
};
14+
15+
if (!isMainThread) {
16+
const sharedArray = workerData.arr;
17+
const result = fb.iterate(workerData.iterations);
18+
/**
19+
* Adds items to the shared array in a safe way
20+
*/
21+
Atomics.add(sharedArray, workerData.position, result.ms);
22+
parentPort.postMessage(sharedArray);
23+
}
24+
25+
module.exports = runFibonacci;

0 commit comments

Comments
 (0)