erlang 并发spawn部分学习

来源:互联网 发布:淘宝商城眼镜 编辑:程序博客网 时间:2024/06/06 02:16

本文的格式为:代码—>debug时查看到的各进程运行的状况及最终总结。
start(N) ->
Pid = my_spawn(spawn_fun,N),
io:format(“the pid is ~p~n”,[Pid]),
Pid.

my_spawn(Func,N) ->
Monitor = spawn(fun() ->
Fs = list_func(N,[],spawn_fun),
io:format(“Module name is ~p~n”,[?MODULE]),
Id = [spawn_link(?MODULE,F,[])||F <- Fs],%%这个spawn_link的第二个参数要为一个原子类型
receive
{‘DOWN’,_,process,Pid,Why} ->
io:format(“Pid:~p quit,Reason:~p~n”,[Pid,Why]),
io:format(“正在重启进程~n”),
spawn_link(Func),
io:format(“重启完毕~n”)
after 15000 ->
exit(“test test test”)
%% io:format(“is List ~p,the list is ~p~n”,[is_list(Id),Id]),
%% lists:min(Id) ! {ok,”exit test”}
end
end),
io:format(“Monitor:~p~n”,[Monitor]),
Monitor.

spawn_fun() ->
io:format(“hello world:~p~n”, [self()]),
receive
{ok,Message} ->
io:format(“about to exit!~p~n”,[self()]),
exit(Message)
after 30000 ->
io:format(“about to exit now!”),
exit(“test”)
end.

%%spawn_fun() ->
%% io:format(“hello world:~p~n”, [self()]),
%% receive
%% {ok,Message} ->
%% io:format(“about to exit!~p~n”,[self()]),
%% exit(Message);
%% other ->
%% spawn_fun()
%% end.

list_func(N,H,F) when N =/= 1 ->
list_func(N-1,[F|H],F);
list_func(N,H,F) when N =:= 1 ->
[F|H].

这里写图片描述
这里写图片描述
start(N) ->
Pid = my_spawn(spawn_fun,N),
io:format(“the pid is ~p~n”,[Pid]),
Pid.

my_spawn(Func,N) ->
Monitor = spawn(fun() ->
Fs = list_func(N,[],spawn_fun),
io:format(“Module name is ~p~n”,[?MODULE]),
Id = [spawn_link(?MODULE,F,[])||F <- Fs],%%这个spawn_link的第二个参数要为一个原子类型
receive
{‘DOWN’,_,process,Pid,Why} ->
io:format(“Pid:~p quit,Reason:~p~n”,[Pid,Why]),
io:format(“正在重启进程~n”),
spawn_link(Func),
io:format(“重启完毕~n”)
%% after 15000 ->
%% exit(“test test test”)
%% io:format(“is List ~p,the list is ~p~n”,[is_list(Id),Id]),
%% lists:min(Id) ! {ok,”exit test”}
end
end),
io:format(“Monitor:~p~n”,[Monitor]),
Monitor.

spawn_fun() ->
io:format(“hello world:~p~n”, [self()]),
receive
{ok,Message} ->
io:format(“about to exit!~p~n”,[self()]),
exit(Message)
after 5000 ->
io:format(“about to exit now!”),
exit(“test”)
end.

%%spawn_fun() ->
%% io:format(“hello world:~p~n”, [self()]),
%% receive
%% {ok,Message} ->
%% io:format(“about to exit!~p~n”,[self()]),
%% exit(Message);
%% other ->
%% spawn_fun()
%% end.

list_func(N,H,F) when N =/= 1 ->
list_func(N-1,[F|H],F);
list_func(N,H,F) when N =:= 1 ->
[F|H].
这里写图片描述
第一种情况是15s后monitor进程退出后,在其基础上裂分出来的子进程都挂了。

第二种情况是5s后子进程都退出后,父进程即monitor进程也退出了,且退出原因一样,monitor进程没能接收到子进程发来的{‘DOWN’,_,process,Pid,Why}消息。
下面是对普通spawn操作的一些测试,请参照代码和图片理解:
这里写图片描述
这里写图片描述
进程接收到一条消息后即退出了
other是一个原子,必须有给当前进程发送other时才能匹配
-module(testspawn).
-author(“Administrator”).

%% API
-export([testspawn/0]).

testspawn() ->
Pid = spawn(fun() ->
receive
{ok,Message} ->
io:format(“received message is:~p~n”,[Message]);
other ->
io:format(“received”)
end
end),
Pid.
这里写图片描述
这里写图片描述
这个是没有使用spawn_link时父子进程的无关联
这里写图片描述
这里写图片描述

0 0
原创粉丝点击