From 62e7fdb06c1c19423f4926851c8382044e2f981c Mon Sep 17 00:00:00 2001 From: AICells <1713699517@qq.com> Date: Fri, 20 Dec 2019 23:17:34 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/arangoApi/genActor.erl | 91 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/arangoApi/genActor.erl diff --git a/src/arangoApi/genActor.erl b/src/arangoApi/genActor.erl new file mode 100644 index 0000000..41cedf3 --- /dev/null +++ b/src/arangoApi/genActor.erl @@ -0,0 +1,91 @@ +-module(genActor). + +-compile(inline). +-compile({inline_size, 512}). + +-export([ + start_link/3, + + init_it/3, + + system_code_change/4, + system_continue/3, + system_get_state/1, + system_terminate/4 +]). + + +-spec start_link(module(), atom(), term(), [proc_lib:spawn_option()]) -> {ok, pid()}. +start_link(Name, Args, SpawnOpts) -> + proc_lib:start_link(?MODULE, init_it, [Name, self(), Args], infinity, SpawnOpts). + +init_it(Name, Parent, Args) -> + case safeRegister(Name) of + true -> + process_flag(trap_exit, true), + moduleInit(Parent, Args); + {false, Pid} -> + proc_lib:init_ack(Parent, {error, {already_started, Pid}}) + end. + +%% sys callbacks +-spec system_code_change(term(), module(), undefined | term(), term()) -> {ok, term()}. +system_code_change(State, _Module, _OldVsn, _Extra) -> + {ok, State}. + +-spec system_continue(pid(), [], {module(), atom(), pid(), term()}) -> ok. +system_continue(_Parent, _Debug, {Parent, State}) -> + loop(Parent, State). + +-spec system_get_state(term()) -> {ok, term()}. +system_get_state(State) -> + {ok, State}. + +-spec system_terminate(term(), pid(), [], term()) -> none(). +system_terminate(Reason, _Parent, _Debug, _State) -> + exit(Reason). + +safeRegister(Name) -> + try register(Name, self()) of + true -> true + catch + _:_ -> {false, whereis(Name)} + end. + +moduleInit(Parent, Args) -> + case ?MODULE:init(Args) of + {ok, State} -> + proc_lib:init_ack(Parent, {ok, self()}), + loop(Parent, State); + {stop, Reason} -> + proc_lib:init_ack(Parent, {error, Reason}), + exit(Reason) + end. + +loop(Parent, State) -> + receive + {system, From, Request} -> + sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {Parent, State}); + {'EXIT', Parent, Reason} -> + terminate(Reason, State); + Msg -> + {ok, NewState} = ?MODULE:handleMsg(Msg, State), + loop(Parent, NewState) + end. + +terminate(Reason, State) -> + ?MODULE:terminate(Reason, State), + exit(Reason). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% need %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +-spec init(Args :: term()) -> {ok, term()}. +init(Args) -> + {ok, {}}. + +-spec handleMsg(Msg :: term(), State :: term()) -> {ok, term()}. +handleMsg(Msg, State) -> + {ok, term}. + +-spec terminate(Reason :: term(), State :: term()) -> ok. +terminate(Reason, State) -> + ok.