스레드 예시(소수 찾기)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
const {
Worker, isMainThread, parentPort, workerData,
} = require('worker_threads');
const min =2;
let 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}}));
start += 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);
}
|
cs |
'개발 > Node.js' 카테고리의 다른 글
[Node.Js] 라우터 분리 (0) | 2023.05.13 |
---|---|
[Node.js] npm WARN config global --global, --local are deprecated. Use --location=global instead. 에러 해결 (1) | 2023.05.13 |