Technomenace

Linux, technology, opensource etc.

Receive Messages With Priority in Erlang

Posted at — Jan 10, 2016
-module(spawntest).
-export([ start/0,
       test/0	]).


start() ->
	register(?MODULE, spawn(fun() -> myfun() end)).

myfun() ->
	receive
		{P, critical, Msg} ->
			do_critical(P, Msg)
	after 0 ->
		receive
			{P, critical, Msg} ->
				do_critical(P, Msg);
			{P, Any} ->
				do_normal(P, Any)
		end
	end,
	myfun().	

do_critical(Pid, Msg) ->
	io:format("Received CRITICAL message from ~p : ~s~n", [Pid, Msg]).


do_normal(Pid, Msg) ->
	io:format("Received NORMAL message from ~p : ~s~n", [Pid, Msg]).

test() ->
	?MODULE ! {self(), critical, critical_message1},
	?MODULE ! {self(), normal_message1},
	?MODULE ! {self(), critical, critical_message2},
	?MODULE ! {self(), critical, critical_message3},
	?MODULE ! {self(), critical, critical_message4},
	?MODULE ! {self(), normal_message2},
	?MODULE ! {self(), normal_message3},
	?MODULE ! {self(), normal_message4}.

% EOF %

Compile and run:

$ erl
Erlang/OTP 17 [erts-6.1] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Eshell V6.1  (abort with ^G)
1> c(spawntest).
{ok,spawntest}
2> spawntest:start().
true
3> whereis(spawntest).
<0.39.0>
4> spawntest:test().
Received CRITICAL message from <0.32.0> : critical_message1
Received CRITICAL message from <0.32.0> : critical_message2
{<0.32.0>,normal_message4}
Received CRITICAL message from <0.32.0> : critical_message3
Received CRITICAL message from <0.32.0> : critical_message4
Received NORMAL message from <0.32.0> : normal_message1
Received NORMAL message from <0.32.0> : normal_message2
Received NORMAL message from <0.32.0> : normal_message3
Received NORMAL message from <0.32.0> : normal_message4