%% --- %% Excerpted from "Programming Erlang", %% published by The Pragmatic Bookshelf. %% Copyrights apply to this code. It may not be used to create training material, %% courses, books, articles, and the like. Contact us if you are in doubt. %% We make no guarantees that this code is fit for any purpose. %% Visit http://www.pragmaticprogrammer.com/titles/jaerlang for more book information. %%--- -module(receivemod). %% commonly used routines -export([sleep/1, flush_buffer/0, priority_receive/0, go/0]). % This function waits T milliseconds before returning sleep(T) -> receive after T -> true end. % flushes all messages from the calling process's mailbox flush_buffer() -> receive _Any -> flush_buffer() after 0 -> true end. % looks through the entirety of the mailbox for a message {alarm,X} % (for any X). If no such message exists, returns the first message. priority_receive() -> receive {alarm, X} -> {alarm, X} after 0 -> receive % why necessary? XXX Any -> Any end end. %% TESTS server_loop() -> case (priority_receive()) of {alarm, Val} -> io:format ("PRIORITY: got ~p~n", [Val]), case Val of flush -> io:format(" (flushed buffer)~n"), flush_buffer(), server_loop(); _Val -> server_loop() end; Val -> io:format ("got ~p~n", [Val]), sleep(200), server_loop() end. go() -> S = spawn(fun () -> server_loop() end), S ! hello, sleep(10), S ! "message", S ! "message2", S ! {alarm, "alert!"}, S ! {alarm, flush}, sleep(200), S ! "bye", ok.