by ricardobeat · 14y ago · 0 comments
var cluster = require('cluster')
, http = require('http')
, os = require('os')
if (cluster.isMaster) {
os.cpus().forEach(cluster.fork)
} else {
http.createServer(function(req, res){
res.writeHead(200)
res.end('Hello world')
}).listen(8000)
}In any case, it's still not an apples to apples comparison. The node.js example forks separate processes that share nothing, while in the Go example it all runs in one process so the HTTP handlers can communicate with each other via channels or other shared data structures.
The documentation has the primary goal of explaining how things work, not being the canonical style guide.
Take a similar example from the Go documentation:
const NCPU = 4 // number of CPU cores
func (v Vector) DoAll(u Vector) {
c := make(chan int, NCPU) // Buffering optional but sensible.
for i := 0; i < NCPU; i++ {
go v.DoSome(i*len(v)/NCPU, (i+1)*len(v)/NCPU, u, c)
}
// Drain the channel.
for i := 0; i < NCPU; i++ {
<-c // wait for one task to complete
}
// All done.
} http = require 'http'
server = http.createServer 'localhost', (req, res) ->
res.writeHead 200
res.end 'ok'
app = server.listen 3000 os.cpus().forEach(cluster.fork)
Should be: os.cpus().forEach(cluster.fork.bind(cluster)); var fork = require('cluster').fork
Cluster methods keep a reference to the main object inside the module, see https://github.com/joyent/node/blob/master/lib/cluster.js#L4...