Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %%% Name :Marcus Näslund
- %%% Personal number :9312105118
- %%% E-mail :
- -module(dist_erlang).
- -record(object, {pid, dbkey, value}).
- %% DO NOT CHANGE THE EXPORT STATEMENT!
- -export([start/0, init/0, stop/0, store/2, fetch/1, flush/0,
- task/1, dist_task/1, pmap/2, faulty_task/1
- ]).
- %% End of no-change area
- start() ->
- case whereis(sts) of
- undefined ->
- Pid = spawn(dist_erlang,init,[]),
- register(sts,Pid),
- {ok,Pid};
- Pid ->
- {ok,Pid}
- end.
- stop() ->
- case whereis(sts) of
- undefined ->
- already_stopped;
- Pid ->
- true = exit(Pid,stop),
- stopped
- end.
- store(Key,Value) ->
- case whereis(sts) of
- undefined ->
- no_server_running;
- Pid ->
- Pid ! {self(),store, Key, Value},
- receive
- Result ->
- Result
- after 1500 ->
- request_timeout
- end
- end.
- fetch(Key) ->
- case whereis(sts) of
- undefined ->
- no_server_running;
- Pid ->
- Pid ! {self(),fetch, Key},
- receive
- Result ->
- Result
- after 1500 ->
- reqest_timeout
- end
- end.
- flush() ->
- case whereis(sts) of
- undefined ->
- no_server_running;
- Pid ->
- Pid ! {self(),flush},
- receive
- Result ->
- Result
- after 1500 ->
- requet_timeout
- end
- end.
- init() ->
- loop([]).
- %% Server loop
- loop(Db) ->
- receive
- {Pid,fetch,Key} ->
- Pid ! fetch(Pid,Key,Db),
- loop(Db);
- {Pid,store,Key,Value} ->
- case fetch(Pid,Key,Db) of
- {ok,_} ->
- ok, Pid ! {ok,Value};
- {error,not_found} ->
- no_value, Pid ! {ok,no_value}
- end,
- Db2 = [#object{pid=Pid,dbkey=Key,value=Value}|Db],
- loop(Db2);
- {Pid,flush} ->
- NewDb = flush(Pid,Db,[]),
- Pid ! {ok,flushed},
- loop(NewDb)
- end,
- loop(Db).
- fetch(Pid,Key,[H|T]) ->
- case H of
- #object{pid=Pid,dbkey=Key} ->
- {ok,H#object.value};
- H ->
- fetch(Pid,Key,T)
- end;
- fetch(_,_,[]) ->
- {error,not_found}.
- flush(Pid,[H|T],Db) ->
- case H of
- #object{pid=Pid} ->
- flush(Pid,T,Db);
- H ->
- flush(Pid,T,[H|Db])
- end;
- flush(_,_,Db) ->
- Db.
Advertisement
Add Comment
Please, Sign In to add comment