您正在寻找的是一个scatter
实用程序,它采用一组元素并将这些元素分配给一组进程。
-module(lab).
-compile(export_all).
go() ->
ProcessList =
lists:map(fun(_) ->
spawn(?MODULE, echo, [])
end,
lists:seq(1, 6)),
DataList = ["E", "r", "l", "a", "n", "g"],
scatter(DataList, ProcessList).
scatter(DataList, ProcessList) ->
lists:foreach(fun({Data, Process}) ->
Process ! Data
end,
lists:zip(DataList, ProcessList)).
echo() ->
receive
Msg ->
io:format("~p echos ~p~n", [self(), Msg]),
echo()
end.
试试看:
1> c(lab).
{ok,lab}
2> lab:go().
<0.40.0> echos "E"
<0.41.0> echos "r"
<0.42.0> echos "l"
<0.43.0> echos "a"
<0.44.0> echos "n"
<0.45.0> echos "g"
ok