inicio mail me! sindicaci;ón

Toying with Erlang

There’s plenty of messages in the blogosphere about Erlang these days so I’m not gonna make praises for this wonderful tool some more. If you’re interested in concurrency and you had enough with the thread jiggling go check it out and learn message passing with Erlang.

After reading here and there I tried to write a simple pet program dealing with concurrency and I came with a very simple star topology example. You create a bunch of processes and send a message back and forth to them until the counter reaches 0. Nothing can be more simple in the message passing world! You share nothing, you create lightweight processes and you come up with something like this:

% send the message across the ring surrounding the process
% in the center (the main process). If the list of processes
% gets empty a loop is done so start again. When the count
% of bounces reaches 0 we're done.
send(_, _, 0, _) -> 
    exit(normal);
send(Msg, [], N, Orig_Pid_List) ->
    send(Msg, Orig_Pid_List, N, Orig_Pid_List);
send(Msg, [Next_PID | Rest], N, Orig_Pid_List) ->
    Next_PID ! {self(), Msg},
    io:format("sent to ~w~n", [Next_PID]),
    receive
        {Pid, Msg} ->
            io:format("received from ~w~n", [Pid]),
            send(Msg, Rest, N - 1, Orig_Pid_List)
    end.

This is actually the core of the sample. Read the comments to understand it. As you can see Erlang does pattern matching with functions, with receive construct, with case, with if and I guess more. Recursion is also used a lot so get used to it.

I posted the whole “star” example here: http://paste.lisp.org/display/26025.

Related posts

  • Erlang is damn intuitive
  • Erlang and the GUIs
  • Producer/Consumer in Python
  • Gravatar

    Giovanni Corriga said,

    September 14, 2006 @ 3:48 pm

    At the latest ESUG Conference I listened to a speech by Joe Armstrong, the inventor of Erlang.

    Link: http://www.esug.org/conference.....am/erlang/

    Gravatar

    Lawrence said,

    September 14, 2006 @ 4:10 pm

    Cool I heard of it! I follow his blog too. He’s going to write a brand new Erlang book :-)

    Thanks for the pointer

    Gravatar

    links for 2007-05-31 « Bloggitation said,

    May 31, 2007 @ 2:18 am

    […] Toying with Erlang star(N.M) messages passing implementation (tags: erlang programming) […]

    RSS feed for comments on this post · TrackBack URI

    Leave a Comment