DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Erlang Message Passing - Ruby Point Of View

08.14.2007
| 6398 views |
  • submit to reddit
        
#!/usr/bin/env ruby

StartTime = Time.now
MT = Thread.current

$data = [0,0]

class ErProc
  def initialize(*args)
    #create thread
    @thr = Thread.new { func(*args) }
    @waiter = nil
    @data = nil
  end
  
  def func(*args)
    while true
      data = recieve()
      #p data
      data[1] = data[1] + 1
      if nil == args[0]
        $data = data
        MT.wakeup
      else
        args[0].send(data)
      end
    end
  end
  
  def recieve()
    # check waiting
    Thread.critical = true
    if @waiter
      @waiter.wakeup
      @waiter = nil
      Thread.critical = false
    else
      # thread stop
      Thread.stop
    end
    # returns data
    return @data
  end
  
  def send(data)
    # block till thread is running
    Thread.critical = true
    if !@thr.stop?
      @waiter = Thread.current
      Thread.stop
    end
    # strore data
    @data = data
    Thread.critical = false
    # starts thread
    @thr.wakeup
    # return
  end
end

raise "Parameters must be: thread_cnt message_cnt" if ARGV.size != 2

ProcCnt = ARGV[0].to_i
MsgCnt = ARGV[1].to_i

puts "Creating #{ProcCnt} processes"

prev = nil
1.upto(ProcCnt) do
  prev = ErProc.new(prev)
end

puts "Finish: #{Time.now - StartTime}"

puts "Sending #{MsgCnt} messages"

1.upto(MsgCnt) do |x|
  $data[0] = x
  prev.send($data)
  Thread.stop
  p $data
end

puts "Full time :#{Time.now - StartTime}"