Node.js でマルチスレッド: isolate を使ってみた。
(注意: Isolates 機能の開発は中止になりました。 参考 https://groups.google.com/d/topic/nodejs/zLzuo292hX0/discussion )
Nodeの次期バージョンの新機能として予定しているマルチスレッド対応については、先日の「東京Node学園3時限目」で @koichik さんが 東京Node学園#3 Domains & Isolates の講演をされていましたが、今朝ちょうどその実装が master に上がりましたので、ファーストインプレッションとしてisolateを使った Node のマルチスレッドをチト試してみました。
(以下 Disclaimer: ここで紹介したAPIの実装や仕様は今後変わる可能性があります。特に Node はリリース直前でも大きく変わることもありますので、)
現時点で Node の isolate は、child_process モジュールの spawn(), fork() 等を利用して使うことができます。
使うのは簡単で option に { thread: true } のプロパティを加えるだけです。(process の生成が thread の生成に変わるだけです。)
thread を区別するため新しく process.tid 変数が追加され、メインの default のイベントループを持つスレッドは1番で、後はスレッド生成毎に数字がインクリメントしていきます。後スレッド宛にメッセージを送る .send() も追加されています。
で、複数スレッド宛にメッセージをピンポンする簡単なスクリプトを試してみました。
var fork = require('child_process').fork; var thread_number = 10; if(process.tid === 1) { var n = []; for(var i = 0; i < thread_number; i++){ n[i] = fork(__filename, null, {thread: true}); n[i].send("Hello from Main"); n[i].on('message', function(m) { console.log(m); }); } } else { process.on('message', function(m) { process.send("Get "+m+", Reply from thread id:"+process.tid+" of pid:"+process.pid); }); }
結果は、
> ./node isolate.js Get Hello from Main, Reply from thread id:11 of pid:2962 Get Hello from Main, Reply from thread id:7 of pid:2962 Get Hello from Main, Reply from thread id:5 of pid:2962 Get Hello from Main, Reply from thread id:8 of pid:2962 Get Hello from Main, Reply from thread id:9 of pid:2962 Get Hello from Main, Reply from thread id:3 of pid:2962 Get Hello from Main, Reply from thread id:6 of pid:2962 Get Hello from Main, Reply from thread id:10 of pid:2962 Get Hello from Main, Reply from thread id:2 of pid:2962 Get Hello from Main, Reply from thread id:4 of pid:2962
といった感じで、Nodeがマルチスレッドで動作しているのがわかりました。
Nodeのコアチームは、クリスマス休暇や年末年始にもかかわらず精力的に開発を続けており、年末の hashDos 対応も重なり本当に大変だったと思います。
安定性を重視しながら着実に進化している Node の新しいリリースを楽しみに待ちたいと思います。