Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,52 @@
import {Worker} from 'node:worker_threads';
import {cpus} from 'os';
import {dirname} from "../utils/dir.js";

const INCREMENT_START = 10;
const performCalculations = async () => {
// Write your code here
const __dirname = dirname(import.meta.url);
const results = await getWorkerCalculations(cpus().length, `${__dirname}/worker.js`);

results.forEach(result => console.log(result));
};

async function getWorkerCalculations(cores, thread) {
const results = [];

for (let workerCounter = 0; workerCounter < cores; workerCounter++) {
const queuedWorker = new Promise((resolve, reject) => {
const worker = new Worker(
thread,
{
workerData: {
increment: INCREMENT_START + workerCounter
}
}
);

worker.on('message', data => {
resolve({
status: 'resolved',
data: data
});
});

worker.on('error', data => {
reject({
status: 'error',
data: null
});
});
});

try {
results.push(await queuedWorker);
} catch (error) {
results.push({status: 'error', data: null});
}
}

return results;
}

await performCalculations();
8 changes: 6 additions & 2 deletions src/wt/worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
// n should be received from main thread

import {parentPort, workerData} from 'node:worker_threads';

const nthFibonacci = (n) => n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2);

const sendResult = () => {
// This function sends result of nthFibonacci computations to main thread
parentPort.postMessage(
nthFibonacci(workerData.increment)
);
};

sendResult();