"Cleaning" the message queue

Willem Broekema <>
Fri Jul 13 18:01:33 CEST 2001


Heh, this looks like a nice way to compensate for my DOH get_tcp/gen_tcp 
typo question. ;-)

Vlad Dumitrescu wrote:

> What I'd want is that in case there are several such messages waiting, 
> only the latest shall be processed, while the rest shall be dumped. 
> (The messages are "virtual clock ticks")

I came up with the following simple solution:

-module(getlatest).
-export([start/0]).

start() ->
    loop().

loop() ->
    receive
        {From, get_latest} ->
            From ! get_latest(),
            loop()
    end.

get_latest() ->
    get_latest(queue_was_empty).

get_latest(LastUntilNow) ->
%% if there's no new message in the queue, return 'LastUntilNow'
    receive
        Newer ->
            get_latest(Newer)
    after
        0 ->
            LastUntilNow
    end.


And works like:

23> S = spawn_link(getlatest, start, []).
<0.65.0>
24> S ! first.
first
25> S ! second.
second
26> S ! last.
last
27> S ! {self(), get_latest}.
{<0.41.0>,get_latest}
28> flush().
Shell got last
ok
29>

HTH

- Willem




More information about the erlang-questions mailing list