% $Id$ -module(sendreceive). -export([demo1/1,demo2/0,demo3/0]). demo1(N) -> FS = spawn(fun factServer/0), FS! {self(), fact, N}, receive {ok, M} -> M end. % the factServer does a simple RPC, with some error checking. factServer() -> receive {Pid, fact, N} when N >= 0 -> Pid ! {ok, factorial(N)}; {Pid, fact, _N} -> % _N < 0 Pid ! {wrong, 0} end. -spec factorial(integer()) -> integer(). factorial(0) -> 1; factorial(N) -> N*factorial(N-1). % Below, note the use of variables defined outside the scope of receive's demo2() -> Me = self(), FS = spawn( fun () -> receive {Me, fact, N,N} -> Me!{self(), ok, factorial(N)} % can't use FS here end end), FS! {Me, fact, 7, 7}, receive {FS, ok, M} -> M end. % This demo shows how receive processes messages in historical order % using all the clauses in the receive (see receiver/1 below). demo3() -> Me = self(), Server = spawn(fun sender/0), Server!{Me, msg2, 1}, Server!{Me, msg2, 2}, Server!{Me, msg1, 3}, receiver(Me). % The server in demo3; % this sends messages to the Pid it receives in the messages. sender() -> receive {Pid, msg1, N} -> Pid ! {self(), got1, N}; {NPid, msg2,M} -> NPid!{self(), got2, M} end, sender(). % a receive loop that prints each message as it comes in. receiver(Me) -> receive {_SPid, M, N} -> io:format("received ~w number ~w~n", [M,N]) end, receiver(Me).