博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

erlang 练手 进程环

Posted on 2013-07-14 16:20  bobolive  阅读(183)  评论(0编辑  收藏  举报

Erlang 编程指南第四章 练习4-2

编写一个程序,生成N个进程并相连成环,启动环后绕环发送M个消息,当收到退出消息后终止.

ringStart(M,N,Message, Cp) ->
    io:format("ring start ~w|~w|~p~n",[M, N, Message]),
    if
        N > 0 ->
            Pid = spawn(test_pid, ringReader, [N, self(), yes, 0]),
            Pid ! {read, M, Message};
        true -> Pid = Cp
    end,
    receive
        {nextMsg, Ring} when Ring == 0 -> io:format("ring ok",[]);
        {nextMsg, Ring} -> io:format("nest ring start ~w~n",[Ring -1]), Pid ! {read, Ring - 1, Message}, ringStart(Ring -1, 0, Message, Pid)
    end.


ringReader(N, Pid, Flg, Cp) ->
    io:format("start ~w~n",[N]),
    if
        N > 0 andalso Flg == yes ->
            CPid = spawn(test_pid, ringReader, [N-1, Pid, Flg, 0]);
        true -> CPid = Cp
    end,
    receive
        {read, Ring, Msg} -> 
        io:format("Reader ~w receive msg ~p~n",[N, Msg]),
        if
            N == 0 ->
                io:format("P nextMsg ~w~n", [Pid]), Pid ! {nextMsg, Ring};
            true -> CPid ! {read, Ring, Msg}
        end,
         ringReader(N, Pid, no, CPid);
        stop -> io:format("Reader ~w stop ~n",[N])
    end.

运行结果:

通过io:format 可以清楚地看到3个进程结成一个环,并绕环发送了3个消息.