
Untitled
By: a guest on
Jul 4th, 2012 | syntax:
None | size: 2.48 KB | hits: 9 | expires: Never
-module(fridge2).
-compile([export_all]).
start_fridge() ->
spawn(?MODULE, restarter, []).
stop_fridge() ->
compressor ! terminate,
fridge ! terminate.
restarter() ->
process_flag(trap_exit, true),
Pid = spawn_link(?MODULE, fridge, [[{bacon, 45}, {eggs, 60}]]),
register(fridge, Pid),
plugin(),
receive
{'EXIT', Pid, normal} -> % not a crash
ok;
{'EXIT', Pid, shutdown} -> % manual termination, not a crash
ok;
{'EXIT', Pid, _} ->
restarter()
end.
plugin() ->
spawn(?MODULE, restart_compressor, []).
unplug() ->
compressor ! terminate.
restart_compressor() ->
process_flag(trap_exit, true),
Pid = spawn_link(?MODULE, compressor, [5000]),
register(compressor, Pid),
receive
{'EXIT', Pid, normal} -> % not a crash
io:format("The compressor has been unplugged!~n");
{'EXIT', Pid, shutdown} -> % manual termination, not a crash
ok;
{'EXIT', Pid, _} ->
restart_compressor()
end.
compressor(Time) ->
Pid = whereis(fridge),
receive
{Pid, {cooled, FoodList}} ->
io:format("The contents are now:~n~p~n", [FoodList]),
compressor(Time);
terminate ->
ok
after Time ->
fridge ! {self(), {cool, 1}},
compressor(Time)
end.
take(Food) ->
fridge ! {self(), {take, Food}},
Pid = whereis(fridge),
receive
{Pid, {ok, Food}} -> Food
after 2000 ->
timeout
end.
list() ->
fridge ! {self(), list},
Pid = whereis(fridge),
receive
{Pid, Food} -> Food
after 2000 ->
timeout
end.
store(Food, Temp) ->
fridge ! {self(), {store, {Food, Temp}}},
Pid = whereis(fridge),
receive
{Pid, {ok}} -> stored
after 2000 ->
timeout
end.
fridge(FoodList) ->
receive
{From, {store, {Food, Temp}}} ->
From ! {self(), {ok}},
fridge([{Food, Temp}|FoodList]);
{From, {take, Food}} ->
case lists:keyfind(Food, 1, FoodList) of
{Food,Temp} ->
From ! {self(), {ok, Food}},
fridge(lists:delete({Food,Temp}, FoodList));
false ->
From ! {self(), not_found},
fridge(FoodList)
end;
{From, {cool, Degrees}} ->
Cooled = [{Item, Temp - Degrees} || {Item, Temp} <- FoodList, Temp > 43],
Cold = [{Item, Temp} || {Item, Temp} <- FoodList, Temp =< 43],
NewContents = lists:flatten([Cold|Cooled]),
From ! {self(), {cooled, NewContents}},
fridge(NewContents);
{From, list} ->
From ! {self(), FoodList},
fridge(FoodList);
terminate ->
ok
end.