인프런 커뮤니티 질문&답변

abent.developer님의 프로필 이미지
abent.developer

작성한 질문수

[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지

worker_threads

TypeError: Assignment to constant variable.

작성

·

263

0

const {
Worker,
isMainThread,
parentPort,
workerData,
} = require("worker_threads");

const min = 2;
// const max = 10_000_000;
const primes = [];

function findPrimes(start, range) {
let isPrime = true;
const end = start + range;
for (let i = start; i < end; i++) {
for (let j = min; j < Math.sqrt(end); j++) {
if (i !== j && i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(i);
}
isPrime = true;
}
}

if (isMainThread) {
const max = 10_000_000;
const threadCount = 8;
const threads = new Set();
const range = Math.ceil((max - min) / threadCount);
let start = min;
console.time("prime");
for (let i = 0; i < threadCount - 1; i++) {
const wStart = start;
threads.add(
new Worker(__filename, { workerData: { start: wStart, range } })
);
}
threads.add(
new Worker(__filename, {
workerData: { start, range: range + ((max - min + 1) % threadCount) },
})
);

for (let worker of threads) {
worker.on("error", (err) => {
throw err;
});
worker.on("exit", () => {
threads.delete(worker);
if (threads.size === 0) {
console.timeEnd("prime");
console.log(primes.length);
}
});
worker.on("message", (msg) => {
primes = primes.concat(msg);
});
}
} else {
findPrimes(workerData.start, workerData.range);
parentPort.postMessage(primes);
}
 
node:internal/event_target:777 process.nextTick(() => { throw err; }); ^ TypeError: Assignment to constant variable. at Worker.<anonymous> (/Users/itaewon/Documents/devsource/node_test/prime-worker.js:60:14) at Worker.emit (node:events:390:28) at MessagePort.<anonymous> (node:internal/worker:232:53) at MessagePort.[nodejs.internal.kHybridDispatch] (node:internalevent_target:562:20) at MessagePort.exports.emitMessage (node:internal/per_context/messageport:23:28)

답변 1

1

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

let primes = [] 입니다

abent.developer님의 프로필 이미지
abent.developer

작성한 질문수

질문하기