Chinaunix首页 | 论坛 | 博客
  • 博客访问: 99719
  • 博文数量: 18
  • 博客积分: 681
  • 博客等级: 中士
  • 技术积分: 295
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-17 13:33
文章分类
文章存档

2012年(8)

2011年(10)

分类: Python/Ruby

2011-12-06 20:16:07

之前的进程环使用的进程PidCreate具有两个功能:
  1. 创建所有的进程,PidN,PidN-1,...,Pid1,而这些进程只负责接收发送消息;
  2. 把进程PidN发的消息转发给Pid1。
其实,可以递归地创建进程,即Pidi要创建Pidi+1,Pidi+1创建Pidi+2,直到PidN。进程PidN需要往Pid1发送消息,因此Pid1需要注册,这里注册为ring。这样,得到以下的程序:

-module(ring2).
-export([start/1, send_msg/1, stop/0]).
-export([create_process/2]).

start(N) -> call({start, N}).
send_msg(Msg) -> call({send_msg, Msg}).
stop() -> call(stop).

call({start, N}) ->
    Pid = spawn(?MODULE, create_process, [1, N]),
    register(ring, Pid);
call({send_msg, Msg}) ->
    ring ! {ok, Msg};
call(stop) ->
    ring ! stop.
   
% `进程1创建进程2,进程2创建进程3,...,进程n-1创建进程n`
create_process(I, N) when I< N ->
  Pid = spawn(?MODULE, create_process, [I+1, N]),
  send_loop(Pid);
create_process(I, N) when I==N ->
  send_loop(ring).

send_loop(Pid) ->
  receive
    {ok, Content} -> io:format("Pid:~p, Msg:~p~n", [self(), Content]),
             timer:sleep(10000), % sleep 10 seconds
             Pid ! {ok, Content},
                     send_loop(Pid);
    stop          -> ok
  end.


对比之前的和本节的进程创建方法,前者在1个进程内,即PidCreate创建所有进程,后者使用递归地方法创建进程,即进程1创建进程2,进程2创建进程3,直到进程n。下图展示了这两种不同的进程创建方式。



阅读(1538) | 评论(0) | 转发(0) |
0

上一篇:进程环

下一篇:一个Erlang例子的分析

给主人留下些什么吧!~~