message passing to processes, threads, or any combination is über simple in ruby
This file contains 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
# it's easy, in ruby, to setup a worker farm that utilizes processes, threads, | |
# or any combination. the following code sets up three processes, each with | |
# three worker threads, and a super simple, message passing api, to send | |
# messages to any process, which will use one of it's threads to do work | |
# | |
# | |
slaves = Array.new(3){ Slave.new{ Worker.new }} | |
workers = slaves.map(&:object) | |
a, b, c = workers | |
p '_.pid' => Process.pid | |
p 'a.pid' => a.pid | |
p 'b.pid' => b.pid | |
p 'c.pid' => c.pid | |
a.message('hai via a...') | |
a.relay('hai via a via b...', b) | |
a.relay('hai via a via b via c...', b, c) | |
sleep | |
output = <<-__ | |
"_.pid"=>45009} | |
{"a.pid"=>45029} | |
{"b.pid"=>45030} | |
{"c.pid"=>45031} | |
45029 - 70299573942200 - hai via a... | |
45030 - 70299573562400 - hai via a via b... | |
45030 - 70299573942200 - hai via a via b via c... | |
__ | |
BEGIN { | |
require 'thread' | |
require 'rubygems' | |
require 'slave' | |
class Worker | |
attr_accessor :q | |
attr_accessor :threads | |
def initialize | |
@q = Queue.new | |
@threads = Array.new(3) do | |
Thread.new(@q) do |q| | |
Thread.current.abort_on_exception = true | |
loop do | |
msg = q.pop | |
STDERR.puts [Process.pid, Thread.current.object_id, msg].join(' - ') | |
end | |
end | |
end | |
end | |
def message(msg) | |
q.push(msg) | |
end | |
def relay(msg, *args) | |
other = args.shift | |
other ? other.message(msg) : message(msg) | |
end | |
def pid | |
Process.pid | |
end | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment