[Eventmachine-talk] Erlang-like Processes

Francis Cianfrocca
Mon, 27 Aug 2007 13:10:02 -0000

All: I''ve added in the first implementation of Erlang-like processes.
It''s
in the current EM head revision. Unit tests are in tests/test_spawn.rb.

Thanks to James Edward Gray II for looking over the interface and making me
realize that the first version really sucked. This one is very nice.

Even if you''re not into Erlang, you might have noticed the recent
ruby-core
discussions about Fibers. These are basically non-scheduled threads intended
to achieve lightweight concurrency. Your program is supposed to schedule
them, and they run until your code tells them to yield.

Erlang processes are a different approach to the same idea. A
"process" is
basically a data structure and a message queue. Your program can
"spawn"
(create) any number of processes (millions, if it wants to), and you can
send "messages" to any process at any time. The messages carry
parameters
and cause the code in the process to execute to completion with the given
parameters. Code that executes inside a process can send messages back to
the same process or to other processes. Note that when you send a message to
a process, the message does not execute immediately, but rather is scheduled
for execution at some future time. The send-message call returns
immediately.

EM now has essentially the same idea, except that "notify" is used in
place
of "send," which already has a different meaning in Ruby.
Here''s an
implementation of fibonacci with 25 processes:

EM.run {
  x = 1
  y = 1

  25.times {
    s = EM.spawn { x,y = y,x+y }
    s.notify
  }

  rslt = EM.spawn {
    puts "Fibonacci result: #{y}"
    EM.stop
  }
  rslt.notify
}


You could also do the same thing with a single worker process, and notify it
25 times.

This is actually a rather crummy sample because it assumes that the
notification of the rslt object will take place after the notifications of
the fibonacci processes. On a uniprocessor, that assumption will be valid.

Next steps are: 1) to improve the performance; 2) add message filtering like
Erlang has, which will allow you to just dump messages into a queue, and one
or processes will respond to it based on parameters of the message; and 3)
allow you to send messages to spawned processes that are actually running in
other "real" processes, or on different machines.

Comments? Suggestions?
-------------- next part --------------
An HTML attachment was scrubbed...