MulticoreInfo.com header image 2

Interaction between processes, Concurrency: Ring Code in Erlang

February 28th, 2009 · 1 Comment




By Michael Murray
“Solution to the Rrlang ring problem: Write a function which starts N processes in a ring, and sends a message M times around all the processes in the ring. After the messages have been sent the processes should terminate gracefully.

This solution is perhaps more complex than other solutions on the web, one of the reasons is that each node knows about the node before and after it (other solutions just make each node know about the node after it). The reason is so that we can be sure that the message is making the correct path around the ring.”

Full Story

  • Share/Save/Bookmark

Tags: MulticoreInfo · Programming

Like what you're reading? Come back every day for multicore news, or subscribe to RSS updates.



Stumble It!     


1 response so far ↓

  • 1 Bogdan Puscas // Jul 1, 2009 at 12:17 pm

    Try this…

    -module(proces).
    -export([do_ring/1, loopx/0, loopm/3, do_test/0]).

    do_ring(N) -> A = spawn(proces,loopx,[]),
    A ! {create, A, N-1},
    A.

    loopm(Pid0,NextPid, N) -> receive
    0 ->
    %% _ = io:format(”~s ~b~n”,["0 in node", N]),
    %% _ = io:format(”~w ~n”, [now()]),
    loopm(Pid0, NextPid, N);
    die ->
    %% _ = io:format(”~s ~b~n”,["die in node", N]),
    NextPid ! die;
    M when NextPid == Pid0 ->
    %% _ = io:format(”~b ~s ~b~n”,[M,"in node!", N]),
    NextPid ! M-1,
    loopm(Pid0, NextPid, N);
    M ->
    %% _ = io:format(”~b ~s ~b~n”,[M,"in node", N]),
    NextPid ! M,
    loopm(Pid0, NextPid, N)
    end.

    loopx() -> receive
    {create, Pid0, 0} ->
    loopm(Pid0,Pid0, 0);
    {create, Pid0, N} ->
    A = spawn(proces, loopx, []),
    A ! {create, Pid0, N-1},
    loopm(Pid0,A,N)
    end.

    do_test() ->
    P = do_ring(5000),
    _ = io:format(”~w ~n”, [now()]),
    P ! 1000,
    _ = io:format(”~w ~n”, [now()]).