Created
December 13, 2016 14:08
-
-
Save costajob/4d9ad83417b6a540f8bbec6cf6413245 to your computer and use it in GitHub Desktop.
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
require "http/server" | |
class Cluster | |
def initialize(@n : Int32, @port : Int32, @io : IO = STDOUT) | |
@workers = Array(Process).new | |
@pid = Process.pid | |
end | |
def call | |
head | |
@n.times do |i| | |
@workers << Process.fork do | |
log(i) | |
server.listen | |
end | |
end | |
sleep | |
ensure | |
kill_all | |
end | |
private def kill_all | |
@workers.each(&.kill) | |
end | |
private def server | |
HTTP::Server.new(@port) do |context| | |
context.response.print "Hello World" | |
end | |
end | |
private def head | |
@io.puts "[#{@pid}] * Listening on tcp://0.0.0.0:#{@port}", "[#{@pid}] Use Ctrl-C to stop" | |
end | |
private def log(i) | |
@io.puts "[#{@pid}] - Worker #{i} (pid: #{Process.pid}) booted" | |
end | |
end | |
n = ARGV[0]? || "4" | |
cluster = Cluster.new(n.to_i, 9292) | |
cluster.call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment