Created
April 13, 2018 12:54
-
-
Save kurogelee/35fa2069d3f942b4edd7f2f745db4d0d to your computer and use it in GitHub Desktop.
マルチプロセス(マルチスレッド)でのFizzBuzzって? ref: https://qiita.com/kurogelee/items/79df8ad282dd3fc63354
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> Executing task: npm-run ts-node src/fizzbuzz.ts < | |
Map { | |
1 => '1', | |
2 => '2', | |
3 => 'Fizz', | |
4 => '4', | |
5 => 'Buzz', | |
6 => 'Fizz', | |
7 => '7', | |
8 => '8', | |
9 => 'Fizz', | |
10 => 'Buzz', | |
11 => '11', | |
12 => 'Fizz', | |
13 => '13', | |
14 => '14', | |
15 => 'FizzBuzz', | |
16 => '16', | |
17 => '17', | |
18 => 'Fizz', | |
19 => '19', | |
20 => 'Buzz', | |
21 => 'Fizz', | |
22 => '22', | |
23 => '23', | |
24 => 'Fizz', | |
25 => 'Buzz', | |
26 => '26', | |
27 => 'Fizz', | |
28 => '28', | |
29 => '29', | |
30 => 'FizzBuzz' } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as cluster from "cluster"; | |
import * as events from "events"; | |
events.EventEmitter.defaultMaxListeners = 30; | |
function* range(begin: number, end: number) { | |
for (let i = begin; i <= end; i++) { | |
yield i; | |
} | |
} | |
function fizzbuzz(i: number) { | |
return i % 15 === 0 ? "FizzBuzz" | |
: i % 5 === 0 ? "Buzz" | |
: i % 3 === 0 ? "Fizz" | |
: i.toString(); | |
} | |
async function main() { | |
if (cluster.isMaster) { | |
const promises = Array.from(range(1, 30)).map((i) => { | |
return new Promise<[number, string]>((resolve) => { | |
cluster.on("message", (worker, [index, result]: [number, string]) => { | |
if (i === index) { | |
resolve([i, result]); | |
} | |
}); | |
}); | |
}); | |
for (const i of range(1, 30)) { | |
const worker = cluster.fork(); | |
worker.on("online", () => { | |
worker.send(i); | |
}); | |
} | |
const map = new Map(await Promise.all(promises)); | |
console.log(map); | |
Object.values(cluster.workers).forEach((w) => w!.kill()); | |
} else { | |
process.on("message", (i) => { | |
process.send!([i, fizzbuzz(i)]); | |
}); | |
} | |
} | |
if (require.main === module) { | |
main(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment