Reputation: 177
How do I implement a simultaneous passing from all values in a List A, to a List of Processes B? Both List A & B are of equal size. Let's say A = [1,2,3] and B = [<0.42.0>,<0.43.0>,<0.44.0>]. I want to pass the value 1 to process <0.42.0> and so on in parallel execution.
Here is what I came up so far:
pass_values([P|ValueListA], [H|ProcessListB]) ->
H ! {foo, P},
pass_values(ValueListA, ProcessListB).
Upvotes: 0
Views: 253
Reputation: 2880
What you are looking for is a scatter
utility that takes an array of elements and distributes the elements to an array of processes.
-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.
Give it a try:
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
Upvotes: 1