Advertisement
Guest User

Untitled

a guest
Jun 2nd, 2019
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 2.02 KB | None | 0 0
  1. init_acc() ->
  2.     spawn(u8, konto, [0]).
  3.  
  4. send_queries(Server, Amount, From, To) ->
  5.     From ! {transfer_to, Amount, Server},
  6.     To ! {transfer_from, Amount, Server}.
  7.  
  8. send_commit(From, To) ->
  9.     From ! {commit},
  10.     To ! {commit},
  11.     {success, transaction_successfully_commited}.
  12.  
  13. send_abort(From, To) ->
  14.     From ! {abort},
  15.     To ! {abort},
  16.     {failure, transaction_successfully_failed}.
  17.  
  18. divine_intervention(Amount, To) ->
  19.     To ! {transfer_from, Amount, self()},
  20.     receive
  21.         {ready} -> To ! {commit}
  22.     end,
  23.     get_balance(To).
  24.  
  25. get_balance(Konto) ->
  26.     Konto ! {balance, self()},
  27.     receive
  28.         Balance -> Balance
  29.     end.
  30.  
  31. transfer(Amount, From, To) ->
  32.     send_queries(self(), Amount, From, To),
  33.     receive
  34.         {failed} ->
  35.             {error, account_failure};
  36.         {ready} ->
  37.             receive
  38.                 {failed} -> {error, account_failure};
  39.                 {ready} ->
  40.                     send_commit(From, To),
  41.                     B1 = get_balance(From),
  42.                     B2 = get_balance(To),
  43.                     io:format("Konto 1: ~w~nKonto 2: ~w~n", [B1, B2])
  44.         end
  45.     end.
  46.    
  47.  
  48. konto(Balance) ->
  49.     receive
  50.         {transfer_to, Amount, PID} ->
  51.             if
  52.                 Amount =< Balance ->
  53.                     PID ! {ready},
  54.                     transfer_to(Balance, Amount);
  55.                 Amount > Balance ->
  56.                     PID ! {failed},
  57.                     transfer_to(Balance, 0)
  58.             end;
  59.         {transfer_from, Amount, PID} ->
  60.             PID ! {ready},
  61.             transfer_from(Balance, Amount);
  62.         {balance, PID} -> PID ! Balance,
  63.             konto(Balance)
  64.     end.
  65.  
  66. transfer_to(Balance, Amount) ->
  67.     receive
  68.         {commit} ->
  69.             konto(Balance - Amount);
  70.         {abort} ->
  71.             konto(Balance)
  72.     end.
  73.  
  74. transfer_from(Balance, Amount) ->
  75.     receive
  76.         {commit} ->
  77.             konto(Balance + Amount);
  78.         {abort} ->
  79.             konto(Balance)
  80.     end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement