Skip to content

Instantly share code, notes, and snippets.

@NicMcPhee
Last active December 14, 2015 15:29
Show Gist options
  • Save NicMcPhee/5108523 to your computer and use it in GitHub Desktop.
Save NicMcPhee/5108523 to your computer and use it in GitHub Desktop.
A simple Erlang example showing that messages that aren't immediately processed aren't lost, but are held for possible matching later. If you spawn a process P in the wait state initially, msg messages that are sent to it are not processed, but they're not lost, they're just held in the mailbox. When you then switch P to it's run state, then it …
%% @author mcphee
%% @doc A simple example showing that messages that
%% aren't immediately processed aren't lost, but are
%% held for possible matching later.
-module(message_queue).
-export([wait/0, run/0]).
% P = spawn(message_queue, wait, [])
% None of these messages are processed because P starts
% out in the wait state, which doesn't deal with msg
% messages.
% P ! {msg, 0}
% P ! {msg, 1}
% P ! {msg, 2}
% When we switch to the run state, however, by sending
% P the start message, then we process all those queued
% up messages.
% P ! start
wait() ->
receive
start ->
io:format("Got the start message~n"),
run()
end.
run() ->
receive
{msg, N} ->
io:format("Got message ~w~n", [N]),
run();
stop ->
true
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment