Guest User

Untitled

a guest
Jan 21st, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. -module(my_db).
  2. -export([start/0, write/2, stop/0, init/0, read/1, delete/1, match/1, loop/1]).
  3.  
  4. start() ->
  5. register(my_db, spawn(?MODULE, init, [])), ok.
  6.  
  7. init() ->
  8. Db = [],
  9. loop(Db).
  10.  
  11. %% The Client Functions
  12. stop() -> call(stop).
  13. write(Key, Element) -> call({ write, Key, Element }).
  14. read(Key) -> call({ read, Key }).
  15. delete(Key) -> call({ delete, Key }).
  16. match(Element) -> call({ match, Element }).
  17.  
  18. call(Message) ->
  19. my_db ! { request, self(), Message },
  20. receive
  21. { reply, Reply } -> Reply
  22. end.
  23.  
  24. reply(Pid, Reply) -> Pid ! { reply, Reply }.
  25.  
  26. loop(Db) ->
  27. receive
  28. { request, Pid, { write, Key, Element }} ->
  29. io:format("Write: ~p in ~p~n", [{Key, Element}, self()]),
  30. NewDb = db:write(Key, Element, Db),
  31. reply(Pid, ok),
  32. loop(NewDb);
  33. { request, Pid, { read, Key }} ->
  34. io:format("Read : ~p in ~p~n", [Key, self()]),
  35. reply(Pid, db:read(Key, Db)),
  36. loop(Db);
  37. { request, Pid, { match, Element}} ->
  38. io:format("Match: ~p in ~p~n", [Element, self()]),
  39. reply(Pid, db:match(Element, Db)),
  40. loop(Db);
  41. { request, Pid, { delete, Key }} ->
  42. io:format("Delete: ~p in ~p~n", [Key, self()]),
  43. NewDb = db:delete(key, Db),
  44. reply(Pid, ok),
  45. loop(NewDb);
  46. { request, Pid, stop } ->
  47. io:format("Stop: in ~p~n", [self()]),
  48. reply(Pid, ok)
  49. end.
Add Comment
Please, Sign In to add comment