gpt4 book ai didi

erlang - 如何在 Erlang 中生成可变数量的 gen_server

转载 作者:行者123 更新时间:2023-12-02 21:01:39 24 4
gpt4 key购买 nike

目前,我正在将 lists:foreachspawn_link 结合使用,为项目启动可变数量的“workers”,即在启动时确定的workers 数量。我希望每个工作人员都是一个 gen_server,这样我就可以在其中调用异步或同步消息(gen_server:cast 等),这可能吗?

最佳答案

是的,这是可能的。

您可以使用simple_one_for_one: http://erlang.org/doc/man/supervisor.html#start_child-2

a simplified one_for_one supervisor, where all child processes are dynamically added instances of the same process type.

这是一个代码示例:master.erl 是一个主管:

-module(master).

-behaviour(supervisor).

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

%% Supervisor callbacks
-export([init/1]).

-define(SERVER, ?MODULE).

start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).

init([]) ->
RestartStrategy = simple_one_for_one,
MaxRestarts = 1000,
MaxSecondsBetweenRestarts = 3600,

SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},

Restart = permanent,
Shutdown = 2000,
Type = worker,

AChild = {'worker', {'worker', start_link, []},
Restart, Shutdown, Type, ['worker']},

{ok, {SupFlags, [AChild]}}.

worker.erl 是童工:

-module(worker).

-behaviour(gen_server).

%% API
-export([start_link/0]).
-export([start_link/1]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).

-define(SERVER, ?MODULE).

-record(state, {}).

start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
start_link(I) ->
ServerName = lists:flatten(io_lib:format("~p~p", [?SERVER, I])),
io:format("I am ~p~n", [list_to_atom(ServerName)]),
gen_server:start_link({local, list_to_atom(ServerName)}, ?MODULE, [], []).

init([]) ->
{ok, #state{}}.


handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.

handle_cast(calc, State) ->
io:format("result 2+2=4~n"),
{noreply, State};
handle_cast(calcbad, State) ->
io:format("result 1/0~n"),
1 / 0,
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.

handle_info(_Info, State) ->
{noreply, State}.


terminate(_Reason, _State) ->
ok.

code_change(_OldVsn, State, _Extra) ->
{ok, State}.

在 erlang shell 中:

22> master:start_link().                                                               
{ok,<0.2475.0>}
23> lists:map(fun(X) -> supervisor:start_child(master, [X]) end, lists:seq(1, 10)).

关于erlang - 如何在 Erlang 中生成可变数量的 gen_server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37956880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com