Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module (explain).
- -export ([start/1, add/2]).
- %% Lets start a process
- %% This process will be given the name bound to Name
- %% This is converted to a GUID and sent to the loop
- %% left and right are placeholders for the left and right neighbour
- start(Name) -> GUID = erlang:md5(Name),
- spawn(fun() -> loop(dict:new(),
- GUID,
- left,
- right)
- end).
- %% Remote Procedure Call takes care of all the communication
- rpc(Pid, Request) ->
- Pid ! {self(), Request},
- receive
- {Pid, Response} ->
- Response
- end.
- %% Add a contact to the given Pid
- add(Pid, Contact) -> rpc(Pid, {add, Contact}).
- %% Our main loop
- loop(Contacts, GUID, Left, Right) ->
- receive
- %% We receive a touple
- {From, Request} ->
- %% The handle_request always returns a result, the contact list, the left and right neighbour
- {Res, Updated, NewLeft, NewRight} = handle_request(Request, Contacts, GUID, Left, Right),
- %% Lets send the result back to whom ever asked for it
- From ! {self(), Res},
- %% Lets run again
- loop(Updated, GUID, NewLeft, NewRight)
- end.
- %% Handles all the requests from the remote procedure calls
- handle_request(Request, Contacts, GUID, Left, Right) ->
- case Request of
- %% The add method already finds the correct peer, so we just add the contact
- {add, Contact} ->
- {Name, _, _} = Contact,
- case dict:is_key(Name, Contacts) of
- true -> {{error, Name, is_already_there},
- Contacts,
- Left,
- Right};
- false -> {ok,
- dict:store(Name, Contact, Contacts),
- Left,
- Right}
- end;
- Other -> {{error, unknown_request, Other},
- Contacts,
- Left,
- Right}
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement