我是Erlang的初学者。我想用它来观察“教科书”分布式算法(领导选举,共识......)的教学目的的执行情况。在那个阶段,我将我的系统的拓扑描述为一个图(int从int到int列表),并基于此,我创建并初始化其邻居列表。它工作正常,但它似乎有点特设。必须有更通用的方法来做到这一点。常见的库或工具可以帮助吗?erlang中的分布式算法模拟
如果不是,你认为我在做什么有意义吗?见下文。
-module(control).
-export([init/1, init/4]).
% create N processes 1 .. N and return a dict from
% 1..N to Pids
create(_, 0, Dict) -> Dict ;
create(Module, N, Dict) ->
Id = spawn(Module, proc, [nil]),
Id ! init_state,
create(Module, N-1, dict:append(N, Id, Dict)).
% broadcast a Signal to all processes in Dict
broadcast(Dict, Signal) ->
F = fun (_, [Y]) -> Y ! Signal end,
dict : map (F, Dict),
ok.
% send a Signal to process Dict(I)
send(Dict, I, Signal) ->
[Id] = dict : fetch(I, Dict),
Id ! Signal,
ok.
% wait for N ok signals
syncr(0) -> ok;
syncr(N) ->
receive
ok -> io : format("ok received ~n", []), syncr(N-1)
end.
% init neighbors according to topology Graph
init_topology(Dict, Graph) ->
F = fun(X) -> [Res] = dict : fetch(X, Dict), Res end,
IdToPId = fun(L) -> lists : map(F, L) end,
G = fun (I, [Y]) ->
[LId] = dict : fetch(I, Graph),
LPId = IdToPId(LId),
Y ! {neighbors, LPId, self()} end,
dict : map (G, Dict),
ok.
% init all states with unary function Signal : I -> term.
init_state(Dict, Signal) ->
F = fun (I, [Y]) -> Y ! {init, Signal(I), self()} end,
dict : map (F, Dict),
ok.
% init all process according to the given topology and Signal : I -> term
% returns a pair of function Send and Broadcast
init(Module, N, Graph, Signal) ->
Dict = create(Module, N, dict:new()),
init_topology(Dict, Graph),
init_state(Dict, Signal),
syncr(2 * N),
Send = fun (I, S) -> send(Dict, I, S) end,
Broadcast = fun (S) -> broadcast(Dict, S) end,
{ Send, Broadcast }.
% this is a particular instanciation of a consensus algorithm with
% N nodes
% a complete graph topology
% some initialisation of the process states
% the S and B returned functions allows me to interact with the system
% to start the algorithm for instance
init(N) -> {S, B} = control : init(consensus, N, topology : complete(N), fun(_)
-> random : uniform(1000) end), {S,B}.
Erlang社区的“实用性第一”思维模式的一个很好的例子在这个关于分布式进程注册表环境中的容错的ML线程中进行了说明:http://erlang.org/pipermail/erlang-questions/ 2015年,2月/ 083194.html – zxq9 2015-02-11 22:19:43