[erlang-questions] Process scope variable

Tristan Sloughter t@REDACTED
Thu Feb 19 15:36:36 CET 2015


Why even pass the pid!

-module(terrible).

-export([a/0]).

-export([process_state/1]).

a() ->
    start_process_state(),

    proc_put(a, 10),
    b().

b() ->
    {ok, Value} = proc_get(a),
    Value + 1.

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.



More information about the erlang-questions mailing list