%% @author Rolong
-module(process1).
-compile(export_all).
-define(I(F), io:format(F++"~n", [])).
-define(I(F, A), io:format(F++"~n", A)).
start(Fun)->
spawn(?MODULE,Fun,[]).
%% Usage:
%%
%% 启动进程:Pid = process1:start(Fun).
%% Fun = fun1 | fun3 | fun3 ...
%%
%% 发送消息 Pid ! Message.
%% Message = term()
%%'-------- fun --------
%%'fun1 进程立即结束
%% 用erlang:is_process_alive(Pid)检查进程是否存在
fun1()->
sleep(10),
?I("I'm fun1.~n").
%%.
%%'fun2 进程收到一个消息后结束
%% 用erlang:is_process_alive(Pid)检查进程是否存在
%% 发送消息:Pid ! message
fun2()->
receive
Msg ->
?I("I'm fun2, received: ~p", [Msg])
end.
%%.
%%'fun3 进程不会结束
%% 结束方法:
%% exit(Pid, Reason)
fun3()->
receive
Msg ->
?I("I'm fun3, received: ~p", [Msg]),
%% 回调自己
fun3()
end.
%%.
%%'fun4 增加结束方法
%% 进程收到stop消息后结束
%% 结束方法:
%% 1、 exit(Pid, Reason)
%% 2、 Pid ! stop
fun4()->
receive
stop ->
?I("fun4 received stop."),
%% 不再回调自己,进程结束
ok;
Msg ->
?I("I'm fun4, received:~p", [Msg]),
%% 回调自己
fun4()
end.
%%.
%%'fun5 增加询问功能
%% 询问方法:Pid ! who
fun5()->
receive
who ->
%% TODO: ....
?I("I'm fun5"),
fun5();
stop ->
ok;
Msg ->
?I("I'm fun1, receive:~p", [Msg]),
fun5()
end.
%%.
%%'fun6 进程不会处理处理stop以外的任何消息
%% 未处理的消息会累积在进程消息队列里
%% 用erlang:process_info(Pid)查看进程信息
fun6()->
receive
stop -> ok
end.
%%.
%%'fun7 增加超时处理,超时后结束
%% 进程在8秒内没有收到任何消息就结束
fun7()->
receive
Msg ->
?I("I'm fun7, receive: ~p", [Msg]),
fun7()
after
8000 -> ?I("I'm fun7, timeout, STOP.~n")
end.
%%.
%%'fun8 增加超时处理,超时后不结束
fun8()->
receive
Msg ->
?I("I'm fun8(~w), receive: ~p", [self(), Msg]),
fun8()
after
5000 ->
?I("I'm fun8(~w), 5s elapsed, waiting for you...", [self()]),
fun8()
end.
%%.
%%.fun end
%%'练习1:实现一个sleep函数
-spec sleep(Seconds) -> any() when
Seconds :: integer().
sleep(T) ->
Time = T * 1000,
receive after Time -> ok end.
%%.
%%'练习2:实现一个定时器,如:
%% process1:timer(3, process1, fun1, []).
%% 3秒之后,就会执行fun1函数
-spec timer(Seconds, Mod, Fun, Arg) -> any() when
Seconds :: integer(),
Mod :: atom(),
Fun :: atom(),
Arg :: [term(), ...].
timer(Seconds, Mod, Fun, Arg) ->
spawn(process1, timer1, [Seconds, Mod, Fun, Arg]).
timer1(Seconds, Mod, Fun, Arg) ->
Ms = Seconds * 1000,
receive
after
Ms -> spawn(Mod, Fun, Arg)
% Ms -> Mod:Fun(Arg) %% 参数错误
end.
%%.
%% vim: set filetype=erlang foldmarker=%%',%%. foldmethod=marker:
Erlang入门:进程实例操作与练习1
最新推荐文章于 2021-02-09 10:07:11 发布