编写一个程序,它生成N个进程并相连成环,。一旦启动,这些进程会绕环发送M个消息,然后当收到推出消息的时候正常终止。你可以调用rings:start(N,M,Msg)来启动环。
有两种策略可以完成这个练习,第一种是通过一个中央进程,它设置环并启动发送消息。第二种方法是换里面的新进程产生下一个进程。在编写程序的时候,请确保你的代码在每一个循环迭代中都有很多io:format声明,以检测到底什么发生了,什么没有发生。
http://www.sics.se/~joe/ericsson/du98024.html
不用使用中央管理来标记各个进程,不用保存,看上去好看很多
[img]http://dl.iteye.com/upload/attachment/0081/8263/2369f32a-986d-3137-8c58-ad5777271e56.jpg[/img]
有两种策略可以完成这个练习,第一种是通过一个中央进程,它设置环并启动发送消息。第二种方法是换里面的新进程产生下一个进程。在编写程序的时候,请确保你的代码在每一个循环迭代中都有很多io:format声明,以检测到底什么发生了,什么没有发生。
http://www.sics.se/~joe/ericsson/du98024.html
-module(zog).
%% This is a test program that first creates N processes (that are
%% "connected" in a ring) and then sends M messages in that ring.
%%
%% - September 1998
%% - roland
-export([start/0, start/1, start/2]).
-export([run/2, process/1]). % Local exports - ouch
start() -> start(16000).
start(N) -> start(N, 1000000).
start(N, M) -> spawn(?MODULE, run, [N, M]).
run(N, M) when N < 1 ->
io:format("Must be at least 1 process~n", []),
0.0;
run(N, M) ->
statistics(wall_clock),
Pid = setup(N-1, self()),
{_,T1} = statistics(wall_clock),
io:format("Setup : ~w s", [T1/1000]),
case N of
1 -> io:format(" (0 spawns)~n", []);
_ -> io:format(" (~w us per spawn) (~w spawns)~n",
[1000*T1/(N-1), N-1])
end,
statistics(wall_clock),
Pid ! M,
K = process(Pid),
{_,T2} = statistics(wall_clock),
Time = 1000*T2/(M+K),
io:format("Run : ~w s (~w us per msg) (~w msgs)~n",
[T2/1000, Time, (M+K)]),
Time.
setup(0, OldPid) ->
OldPid;
setup(N, OldPid) ->
NewPid = spawn(?MODULE, process, [OldPid]),
setup(N-1, NewPid).
process(Pid) ->
receive
M ->
Pid ! M-1,
if
M < 0 -> -M;
true -> process(Pid)
end
end.
不用使用中央管理来标记各个进程,不用保存,看上去好看很多
[img]http://dl.iteye.com/upload/attachment/0081/8263/2369f32a-986d-3137-8c58-ad5777271e56.jpg[/img]