[erlang-questions] send after mechanics

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Mon Nov 21 16:12:23 CET 2016


On Sun, Nov 20, 2016 at 10:13 PM nato <nbartley@REDACTED> wrote:

> On a whim, I started an erlang shell, counted the processes (some 25),
> then called `erlang:send_after/3` -- I was surprised to see that the
> count of processes never went up. Do these timer routines not spawn a
> new process!? Seems like a perfect candidate for such. 'Would love
> some hand-holding on how this all works before I stare at the source.
>

In a non-optimizing implementation of Erlang, you might indeed implement
send-after as a process spawn. Something akin to:

send_after(Wait, Target, Msg) ->
    spawn(fun() ->
        receive
        after Wait ->
          Target ! Msg
        end
    end).

In practice you would need to extend the receive clause so it can handle a
cancel-message in the mailbox and return the right value, but this is
somewhat trivial (though it is gritty).

In an optimizing Erlang-implemention, you want timers to be internal in the
system. You want precise wakeup of timers when they trigger and you want
them to have little memory overhead. This guarantees the soft real-time
properties and makes timers fast. So timers are implemented directly in the
runtime, separate from processes.

The "trick" of having a nice "consistent" and "simple" theory which is then
torn down in an industrial practical setting is something you see pretty
often. On one hand, you can understand the system based on its simple
model. And you can verify the correctness of that model against the
practical and fast variant of the system. In fact, there is a direct path
from this observation to monads and their use in proofs.

Another for-efficiency part of the Erlang system are ETS tables, which are
implemented not as processes but as highly optimized concurrently
accessible memory tables. The reason is that Key-Value lookups in mnesia
had the requirement of microsecond latency, and this is not achievable in a
process if the system is under heavy load and that processes is at the end
of the run-queue.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20161121/99fcf714/attachment.htm>


More information about the erlang-questions mailing list