Skip to content

Instantly share code, notes, and snippets.

@darcros
Last active June 27, 2020 19:53
Show Gist options
  • Save darcros/6e773a6d08cb6314cebfc242f6f2f356 to your computer and use it in GitHub Desktop.
Save darcros/6e773a6d08cb6314cebfc242f6f2f356 to your computer and use it in GitHub Desktop.
Concurrent Programming in Erlang - The University of Kent - chapter 1.8
-module(mailbox).
-export([handle_unordered/0, handle_ordered/1, run/0]).
%% Handle messages in the order that they arrive
handle_unordered() ->
receive
stop ->
ok;
{_, Message} ->
io:format("Received message: ~s~n", [Message]),
handle_unordered()
end.
%% Handle messages in the order that is passed as argument
handle_ordered(Order) ->
case Order of
[] -> ok;
[Next | Rest] ->
receive
stop ->
ok;
{Next, Message} ->
io:format("Received message: ~s~n", [Message]),
handle_ordered(Rest)
end
end.
send_messages(Pid) ->
Pid ! {third, "The 3rd message"},
Pid ! {fourth, "The 4th message"},
Pid ! {first, "The 1st message"},
Pid ! {second, "The 2nd message"},
timer:sleep(500),
Pid ! stop.
run() ->
io:format("Running unordered~n"),
UnorderedPid = spawn(mailbox, handle_unordered, []),
send_messages(UnorderedPid),
io:format("Running ordered~n"),
OrderedPid = spawn(mailbox, handle_ordered, [[first, second, third, fourth]]),
send_messages(OrderedPid).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment