Commit chapter 12 stuff from last night.

This commit is contained in:
Kyle Isom 2019-04-29 12:36:13 -07:00
parent d88b7f8bcf
commit 6b5d758311
2 changed files with 61 additions and 0 deletions

32
pe/chapter12.erl Normal file
View File

@ -0,0 +1,32 @@
-module(chapter12).
-compile(exportall).
-export([start/2, registrar/0]).
registrar(Client, {Name, Fun}) ->
case whereis(Name) of
undefined ->
Pid = spawn(Fun),
register(Name, Pid),
Client ! {ok, Name, Pid};
Pid -> Client ! {error, exists, Pid}
end.
registrar() ->
receive
{Client, {Name, Fun}} ->
registrar(Client, {Name, Fun}),
registrar();
X -> io:format("Spurious message ~w received~n", [X])
end.
start(AnAtom, Fun) ->
%% start the registrar if it's not been started.
case whereis(registrar_proc) of
undefined ->
Pid = spawn(chapter12, registrar, []),
register(registrar_proc, Pid);
_ -> void
end,
registrar_proc ! {self(), {AnAtom, Fun}},
receive X -> X end.

29
pe/processes.erl Normal file
View File

@ -0,0 +1,29 @@
-module(processes).
-export([max/1]).
%% max(N)
%%
%% Create N processes then destroy them
%% See how much time this takes
max(N) ->
Max = erlang:system_info(process_limit),
RealN = if N > Max -> Max; true -> N end,
io:format("Max allowed processes: ~p~n", [Max]),
statistics(runtime),
statistics(wall_clock),
L = for(1, RealN, fun() -> spawn(fun() -> wait() end) end),
{_, Time1} = statistics(runtime),
{_, Time2} = statistics(wall_clock),
lists:foreach(fun(Pid) -> Pid ! die end, L),
U1 = Time1 * 1000 / RealN,
U2 = Time2 * 1000 / RealN,
io:format("Process spawn time=~p (~p) microseconds~n", [U1, U2]).
wait() ->
receive
die->
void
end.
for(N, N, F) -> [F()];
for(I, N, F) -> [F()|for(I+1, N, F)].