码迷,mamicode.com
首页 > 系统相关 > 详细

Erlang-实现进程环

时间:2015-04-07 09:44:20      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:erlang   并行处理   

M是消息传递数目,N进程数量,Msg是传递的消息

-module(exe3_2).
-export([start/3,stop/0]).

start(M,N,Msg) ->register(ring,spawn(fun()->ring_service(M,N,Msg) end)).

stop() -> ring!stop.

ring_service(M,N,Msg) ->
    Ring=ring_node(N,[]),%Ring是进程环
    send_msg(M,Msg,Ring),
    receive
        stop -> stop_ring(Ring)
    end.

stop_ring([]) ->ok;
stop_ring([H|T]) ->H!stop,
                 stop_ring(T).



send_msg(0,_Msg,_Ring) ->ok;
send_msg(M,Msg,[H|T]) ->H ! {msg,M,Msg},
                        send_msg(M-1,Msg,T ++ [H]).



ring_node(N,Ring) when N>0 
                    ->Next_Pid = spawn(fun() ->loop() end),
                    ring_node(N-1,[Next_Pid|Ring]);
ring_node(0,Ring) ->lists:reverse(Ring).

loop() ->
        receive
            {msg,M,Msg} ->
                io:format("~w:~w:~w~n",[self(),M,Msg]),
                loop();
            stop ->true
        end.

Erlang-实现进程环

标签:erlang   并行处理   

原文地址:http://blog.csdn.net/li8630/article/details/44916165

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!