Created
February 17, 2015 22:33
-
-
Save tsloughter/a2bd3535ffb27a987580 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(terrible). | |
-export([main/0]). | |
-export([run/1, process_state/1]). | |
main() -> | |
proc_lib:spawn_link(?MODULE, run, [hello]), | |
proc_lib:spawn_link(?MODULE, run, [goodbye]), | |
ok. | |
run(X) -> | |
start_process_state(), | |
proc_put(a, X), | |
{ok, Value} = proc_get(a), | |
io:format("A ~p~n", [Value]). | |
start_process_state() -> | |
Pid = self(), | |
proc_lib:spawn_link(?MODULE, process_state, [Pid]), | |
receive | |
ready -> | |
ok | |
end. | |
proc_get(Key) -> | |
Atom = list_to_atom(pid_to_list(self())), | |
Atom ! {get, Key}, | |
receive | |
Result -> | |
Result | |
end. | |
proc_put(Key, Value) -> | |
Atom = list_to_atom(pid_to_list(self())), | |
Atom ! {put, Key, Value}, | |
receive | |
Result -> | |
Result | |
end. | |
process_state(Pid) -> | |
register(list_to_atom(pid_to_list(Pid)), self()), | |
Pid ! ready, | |
process_state(Pid, dict:new()). | |
process_state(Pid, State) -> | |
receive | |
{get, Key} -> | |
Pid ! dict:find(Key, State), | |
process_state(Pid, State); | |
{put, Key, Value} -> | |
case dict:is_key(Key, State) of | |
true -> | |
Pid ! error, | |
process_state(Pid, State); | |
false -> | |
Pid ! ok, | |
process_state(Pid, dict:store(Key, Value, State)) | |
end | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment