Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My colleagues have made some excellent points. I'd also like to mention that the initial intent of the problem is being avoided by registering the processes instead of actually creating a ring. Here is one possible solution:</p> <pre><code>-module(ring). -export([start/3]). -record(message, {data, rounds, total_nodes, first_node}). start(TotalNodes, Rounds, Data) -&gt; FirstNode = spawn_link(fun() -&gt; loop(1, 0) end), Message = #message{data=Data, rounds=Rounds, total_nodes=TotalNodes, first_node=FirstNode}, FirstNode ! Message, ok. loop(Id, NextNode) when not is_pid(NextNode) -&gt; receive M=#message{total_nodes=Total, first_node=First} when Id =:= Total -&gt; First ! M, loop(Id, First); M=#message{} -&gt; Next = spawn_link(fun() -&gt; loop(Id+1, 0) end), Next ! M, loop(Id, Next) end; loop(Id, NextNode) -&gt; receive M=#message{rounds=0} -&gt; io:format("node: ~w, stopping~n", [Id]), NextNode ! M; M=#message{data=D, rounds=R, total_nodes=Total} -&gt; io:format("node: ~w, message: ~p~n", [Id, D]), if Id =:= Total -&gt; NextNode ! M#message{rounds=R-1}; Id =/= Total -&gt; NextNode ! M end, loop(Id, NextNode) end. </code></pre> <p>This solution uses records. If you are unfamiliar with them, read all about them <a href="http://learnyousomeerlang.com/a-short-visit-to-common-data-structures" rel="nofollow">here</a>.</p> <p>Each node is defined by a <code>loop/2</code> function. The first clause of <code>loop/2</code> deals with creating the ring (the build phase), and the second clause deals with printing the messages (the data phase). Notice that all clauses end in a call to <code>loop/2</code> except the <code>rounds=0</code> clause, which indicates that the node is done with its task and should die. This is what is meant by graceful termination. Also note the hack used to tell the node that it's in the build phase - <code>NextNode</code> isn't a pid but rather an integer.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload