Distributed Computing with Ruby
by Phil Tomson

Listing One 
# -----------hello server ------------
require "drb/drb"
class HelloFrom
  def say_hello
    return "hello from " + Socket.gethostname
  end
end
h = HelloFrom.new
h_server = DRb::DRbServer.new("druby://0.0.0.0:5555", h)
h_server.thread.join
#-----------end of hello server-----
 

Listing Two
# ----------- client ------------
 require "drb/drb"
 primary = DRb::DRbServer.new
 ro = DRb::DRbObject.new(nil, "druby://remote:5555")
 puts ro.say_hello

Listing Three
######################################################
# PiTask.rb
# Estimates pi using the Monte Carlo method
# more iterations should produce more accurate results
#######################################################
require "TaskMaster"
class PiTask
   
   def run(iterations)
     hits = 0
     puts "iterations = #{iterations} iterations.type = #{iterations.type}"
     iterations.times { |i|
       #pick a random x,y
       x = rand
       y = rand
       dist = Math.sqrt(x*x + y*y)
       if dist <= 1.0
         hits += 1
       end
     }
     @my_pi = 4*(hits.to_f/iterations.to_f)
     puts "PiTask::run finished -> estimated pi = #@my_pi"
   end

   def harvest
     return @my_pi
   end

end

Listing Four
#####################################################
# master.rb - run on your master machine
#####################################################
require "TaskMaster"

iterations = 1000000
slaveList = ['frodo','sam','merry','pippin']
class PiReporter
  def initialize
    @estimates = []
  end

  def report(pi_est)
    @estimates << pi_est
  end

  def final_report
    sum = 0
    @estimates.each { |est|
      sum += est
    }
    print "The average pi estimate was: "
    print "#{sum/(@estimates.length)}\n"
  end
end
startTime = Time.now
filesToRequire = ["PiTask.rb"]
filesToRequire.each { |file| require file }
distrib = TaskMaster::Distributor.new(slaveList)
distrib.remote_require(filesToRequire)
reporter = PiReporter.new
distrib.reporter = reporter
(distrib.availableSlaves).each {
  distrib.send_task(PiTask.new(),(iterations/distrib.availableSlaves.length))
}
distrib.wait
reporter.final_report
endTime = Time.now
puts "Total time: #{endTime-startTime} seconds"


Listing Five    
#######################################
# slave.rb - run on your slave machines
#######################################
require "TaskMaster"
slaveObj = TaskMaster::Slave.new()
puts "Slave #{Socket::gethostname} started"
slaveObj.wait




2


