The following sample code is from Joe Armstrong's Programming Erlang book:
max(N) ->
Max = erlang:system_info(process_list),
io:format("Maximum allowed processes:~p~n",[Max]),
statistics(runtime),
statistics(wall_clock),
L = for(1, N, fun() -> spawn(fun() -> wait() end) end),
{_, Time1} = statistics(runtime),
{_, Time2} = statistics(wall_clock),
lists:foreach(fun(Pid) -> Pid ! die end, L),
U1 = Time1 * 1000 / N,
U2 = Time2 * 1000 / N,
io:format("Process spawn time=~p (~p) microseconds~n",
[U1, U2]).
My question is dealing with Erlang fundamentals. It looks like Joe used for()
to spawn processes, followed by a lists:foreach
to die them. Is there a reason to use one over the other? Why not use for() again to iterate over the the spawned process list and send them a die message? Is there an efficiency optimization here that I'm missing?
This is the function that is called: set_viewer_values(Value, ViewerSet) -> if ViewerSet /= empty_set -> lists:map(fun(ViewerPid) -> ViewerPid ! {self(), set_value, Value} end, ViewerSet) end.
The List is a structure used to store a collection of data items. In Erlang, Lists are created by enclosing the values in square brackets.
Erlang is a dynamically typed language. Still, it comes with a notation for declaring sets of Erlang terms to form a particular type. This effectively forms specific subtypes of the set of all Erlang terms.
lists:foreach
saves you the trouble of determining the length of the list ahead of time, and of specifying it as an argument. The for
invocation needs to know how long to make the list, so it's necessary. for()
is usually used as a last resort when there's nothing more appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With