Skip to content

Instantly share code, notes, and snippets.

@benoist
Created August 17, 2016 18:21
Show Gist options
  • Save benoist/349ebfa97aa5d69554253bc28eadb9e0 to your computer and use it in GitHub Desktop.
Save benoist/349ebfa97aa5d69554253bc28eadb9e0 to your computer and use it in GitHub Desktop.
require "http/server"
module HTTPCluster
struct Worker
def initialize(@pid : Int32, @master : Int32)
end
def call(port)
yield(port)
end
def kill
Process.kill(Signal::KILL, @pid)
end
end
class Cluster
def initialize(@n : Int32, @handler : HTTP::Handler)
@master = Process.pid
@workers = [] of Worker
end
def start
@n.times do |i|
fork do
worker = Worker.new(Process.pid, @master)
@workers << worker
worker.call(9292 + i) do |port|
puts "Listening on http://127.0.0.1:#{port}"
HTTP::Server.new(port, @handler).listen
end
end
end
loop {}
ensure
stop
end
private def stop
@workers.each(&.kill)
end
end
end
n = ARGV[0]? || 7
require "big"
class HelloWorld < HTTP::Handler
def fib(n)
if n <= 1
BigInt.new(1)
else
fib(n - 1) + fib(n - 2)
end
end
def call(context)
fib(BigInt.new(20))
context.response.content_type = "text/plain"
context.response.print "Hello World"
end
end
cluster = HTTPCluster::Cluster.new(n.to_i, HelloWorld.new)
cluster.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment