Friday, October 30, 2009

Object Calls == Message Passing in Erlang

This content has moved permanently to:
https://blog.jonm.dev/posts/object-calls-message-passing-in-erlang/

2 comments:

Jon Moore said...

Ah, just realized that I could make the init_node and the ring_node the same if I multiplied the message counter out with N*M initially, had each node decrement before passing, and then gracefully die if the counter is < N (meaning it is on its last circuit). Refactor, refactor, refactor.

Dan said...

I handled the stitching of the endpoints without a new message. You could argue that I cheated, but it works since erlang seems to hold the message for a process until it exists (confirmed by adding a sleep before the last node() call). I also counted messages at each node individually which simplified things a bit. Not sure which way I like better.

(sorry, can't use <pre> in a comment)
-module(conc2).
-export([start/2, make_node/2, node/3]).

node(Id, _, 0) ->
  io:format("Node ~p exiting~n", [Id]),
  true;

node(Id, Next, Num_rem) ->
  receive
    M ->
      io:format("Node ~p got msg (~p left)~n", [Id, Num_rem - 1]),
      Next ! M,
      node(Id, Next, Num_rem - 1)
  end.

make_node(1, NMsgs) ->
  spawn(conc2, node, [1, self(), NMsgs]);

make_node(NNodes, NMsgs) ->
  spawn(conc2, node, [NNodes, make_node(NNodes - 1, NMsgs), NMsgs]).

start(NNodes, NMsgs) ->
  First = spawn(conc2, node,
         [NNodes - 1, make_node(NNodes - 2, NMsgs), NMsgs]),
  First ! yo,
  %%timer:sleep(1000),
  node(NNodes, First, NMsgs).