Advertisement
Guest User

Untitled

a guest
Mar 5th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 2.04 KB | None | 0 0
  1. -module(preWeek19).
  2. -compile(export_all).
  3.  
  4. % The following function, when spawned as a process, acts like
  5. % a reference to a shared memory cell
  6. ref(State) ->
  7.     receive
  8.         % Receive a request to retrieve the currenst ate
  9.         {get, P}        -> P!State, ref(State);
  10.         % Recive a request to update the sate
  11.         {put, NewState} -> ref(NewState)
  12.     end.
  13. % The stateful behaviour is implemented via recursion: the
  14. % parameter of the recursive function is the currently "stored"
  15. % value.
  16.  
  17. % Here are two clients which interact with the memory cell reference
  18. % They have some random sleeping in order to show problems with
  19. % non-determinism in concurrency.
  20. client1(Ref, Parent) ->
  21.     % Sleep randomly then get the value of the cell
  22.     timer:sleep(round(rand:uniform()*1000)),
  23.     Ref ! {get, self()},
  24.     receive X ->
  25.         % Sleep randomly then update the memory cell, with X + 1
  26.         timer:sleep(round(rand:uniform()*1000)),
  27.         Ref ! {put, X+1}
  28.     end,
  29.     % Tell the parent process that you are done
  30.     Parent ! done1.
  31.  
  32. client2(Ref, Parent) ->
  33.     % Sleep randomly then get the value of the cell
  34.     timer:sleep(round(rand:uniform()*1000)),
  35.     Ref ! {get, self()},
  36.     receive X ->
  37.         % Sleep randomly then update the memory cell, with X + 2
  38.         timer:sleep(round(rand:uniform()*1000)),
  39.         Ref ! {put, X+2}
  40.     end,
  41.     % Tell the parent process that you are done
  42.     Parent ! done2.
  43.  
  44. % Run preWeek19:example() a few times and see that we get different
  45. % values, i.e., this is non deterministic
  46. example() ->
  47.     % Start a memory cell process, initialised at 0
  48.     Ref = spawn(?MODULE, ref, [0]),
  49.     % Start the two clients
  50.     spawn(?MODULE, client1, [Ref, self()]),
  51.     spawn(?MODULE, client2, [Ref, self()]),
  52.     % Wait to receive notification that they are done
  53.     receive done1 -> done1 end,
  54.     receive done2 -> done2 end,
  55.     % Get the current value of the memory cell and print it
  56.     Ref ! {get, self()},
  57.     receive
  58.          X -> io:fwrite("~s~n", [integer_to_list(X)])
  59.     end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement