TupleSpace Replicator
Eric Hodel | Sun, 30 Apr 2006 02:32:00 GMT
At MindCamp 2.0 I was asked about how you would replicate a TupleSpace. I whipped up the following implementation:
class Rinda::TupleSpaceReplicator
attr_accessor :debug
attr_reader :local_tuplespace, :remote_tuplespace
def initialize(remote_tuplespace, templates)
@local_tuplespace = Rinda::TupleSpace.new
@remote_tuplespace = remote_tuplespace
@templates = templates
@debug = false
@replicators = ThreadGroup.new
end
def replicate
@templates.each do |template|
%w[write take].each do |type|
make_replicator type, template
end
end
end
def make_replicator(event_type, template)
thread = Thread.start do
observer = @remote_tuplespace.notify event_type, template
observer.each do |event, tuple|
break if event == 'close'
@local_tuplespace.send event, tuple
$stderr.puts "master #{event}: #{tuple.inspect}" if @debug
end
end
@replicators.add thread
end
end
The core of this is the make_replicator method. It replicates tuples of the specified template from the remote tuplespace to the local tuplespace.
Here it is in operation:
# master.rb
require 'rinda/tuplespace'
here = 'druby://127.0.0.1:10000'
ts = Rinda::TupleSpace.new
DRb.start_service here, ts
DRb.thread.join
# slave.rb
require 'rinda/tuplespace'
require 'tuplespace_replicator'
here = 'druby://127.0.0.1:10001'
there = 'druby://127.0.0.1:10000'
rts = DRbObject.new_with_uri there
repl = Rinda::TupleSpaceReplicator.new rts, [[nil]]
DRb.start_service here, repl.local_tuplespace
repl.replicate
DRb.thread.join
# test.rb
require 'drb'
ts1 = DRbObject.new_with_uri 'druby://127.0.0.1:10000'
ts2 = DRbObject.new_with_uri 'druby://127.0.0.1:10001'
ts1.write [0]
ts1.write [1]
ts1.write [2]
p ts2.read_all([nil])
ts1.take [0]
ts1.take [1]
ts1.take [2]
p ts2.read_all([nil])
And then we run it!
$ ruby master.rb & [1] 18289 $ ruby slave.rb & [2] 18290 $ ruby test.rb [[0], [1], [2]] [] $no comments
Comments are disabled


Articles