Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Erlang Message Passing - Ruby point of view

#!/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}"

a silly FIFO in Erlang (you should use OTP's queue.erl instead)

-module(fifo).
-export([new/0, loop/0, push/2, pop/1]).

new() ->
    spawn(?MODULE, loop, []).

loop() ->
    receive
        {Pid,pop} ->
            Pid ! {self(),receive {push,X} ->
                                  X
                          end),
            loop()
    end.

push(Fifo,X) ->
    Fifo ! {push,X},
    X.

pop(Fifo) ->
    Fifo ! {self(),pop},
    receive {Fifo,X} ->
            X
    end.

SET+

    set+: func [ ; Inspired by Erlang's list model.
        "Like SET, but words block is dialected."
        words  [any-block!] "Word after | gets remainder of series."
        series [series!]
        /local word= rule=
    ][
        word=: [set word word!]
        rule=: [
            any [
                '| word= (set word series) to end
                | word= (
                    set word pick series 1
                    series: next series
                )
            ]
        ]
        parse words rule=
    ]
    ;set+ [a | rest] [1 2 3 4 5]
    ;set+ [a b | rest] [1 2 3 4 5]
    ;set+ [a b c] [1 2]
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS