Advertisement
Guest User

Untitled

a guest
Jun 21st, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 2.07 KB | None | 0 0
  1. -module (explain).
  2. -export ([start/1, add/2]).
  3.  
  4. %% Lets start a process
  5. %% This process will be given the name bound to Name
  6. %% This is converted to a GUID and sent to the loop
  7. %% left and right are placeholders for the left and right neighbour
  8. start(Name) -> GUID = erlang:md5(Name),
  9.                spawn(fun() -> loop(dict:new(),
  10.                                    GUID,
  11.                                    left,
  12.                                    right)
  13.                      end).
  14.  
  15. %% Remote Procedure Call takes care of all the communication
  16. rpc(Pid, Request) ->
  17.     Pid ! {self(), Request},
  18.     receive
  19.     {Pid, Response} ->
  20.         Response
  21.     end.
  22.    
  23. %% Add a contact to the given Pid
  24. add(Pid, Contact) -> rpc(Pid, {add, Contact}).
  25.    
  26. %% Our main loop
  27. loop(Contacts, GUID, Left, Right) ->
  28.     receive
  29.         %% We receive a touple
  30.         {From, Request} ->
  31.             %% The handle_request always returns a result, the contact list, the left and right neighbour
  32.             {Res, Updated, NewLeft, NewRight} = handle_request(Request, Contacts, GUID, Left, Right),
  33.             %% Lets send the result back to whom ever asked for it
  34.             From ! {self(), Res},
  35.             %% Lets run again
  36.             loop(Updated, GUID, NewLeft, NewRight)
  37.     end.
  38.    
  39. %% Handles all the requests from the remote procedure calls
  40. handle_request(Request, Contacts, GUID, Left, Right) ->
  41.     case Request of
  42.         %% The add method already finds the correct peer, so we just add the contact
  43.         {add, Contact} ->
  44.             {Name, _, _} = Contact,
  45.             case dict:is_key(Name, Contacts) of
  46.                 true  -> {{error, Name, is_already_there},
  47.                           Contacts,
  48.                           Left,
  49.                           Right};
  50.                 false -> {ok,
  51.                           dict:store(Name, Contact, Contacts),
  52.                           Left,
  53.                           Right}
  54.             end;
  55.         Other -> {{error, unknown_request, Other},
  56.                   Contacts,
  57.                   Left,
  58.                   Right}
  59.     end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement