Skip to content

Instantly share code, notes, and snippets.

@geta6
Created February 24, 2013 15:28
Show Gist options
  • Save geta6/5024215 to your computer and use it in GitHub Desktop.
Save geta6/5024215 to your computer and use it in GitHub Desktop.
node.jsのclusterについて
# 全プロセスで共通して実行される
os = require 'os'
http = require 'http'
cluster = require 'cluster'
# 親プロセス起動時に一回だけ呼ばれる
if cluster.isMaster
console.log 'starting...'
# 起動したosのcpuのスレッド数を求める
cpus = os.cpus().length
boot = 0
# cpuの数だけforkしてやる
for i in [0...cpus]
# fork()の返り値はworker
# worker.process.pidにPIDが入ってる
# listeningイベントはforkしたプロセスがlistening状態になった時にfireする
# http.createServer().listen(PORT, function(){ ココ })
cluster.fork().on 'listening', ->
console.log "forked with process id #{@process.pid}"
# 今までに幾つ起動したか、clusterは感知しないので自分で計上する
if ++boot is cpus
console.info "listening on port #{config.port}"
# forkしたプロセスが死亡したときにfireする
# ここでforkしないと、childが全部落ちた時に
# httpサーバを持たない空プロセスになってしまう
cluster.on 'exit', ->
console.log "restart with process id #{cluster.fork().process.pid}"
# childとしてforkされた時に呼ばれるメソッドを書く
else
server = http.createServer (req, res) ->
res.end 'ok'
server.listen 3000
# 最小規模で同等処理を書くと、こうなる
if cluster.isMaster
cluster.fork() for i in [0...os.cpus().length]
cluster.on 'exit', cluster.fork
else
server = http.createServer (req, res) ->
res.end 'ok'
server.listen 3000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment