Re:When is a recursive function not a recursive function?
by derefr on Sunday October 05, 2014 @11:59AM
(#8412576)
Functions referring to themselves by name is what allows Erlang's hot-code-upgrade to happen.
There are two types of function call opcodes in the BEAM VM: local calls, which call a function by offset within the same module they're defined in; and remote calls, which store module and function name symbolically, and pass them off to the code server to dereference.
All you have to do is update which module is referred to by a given symbol in the code server's module table, and then all remote calls to that module will jump to the new module's code instead of the old one's. Since the idiomatic way to define an Erlang process is in terms of a message-loop step function that makes a remote recursive-tail-call to itself at the end, each process will silently "jump into" the newest version of its module code after each message-loop step.
(Possibly more interesting for some of you is the fact that all loops in Erlang are defined in terms of tail-call-optimized recursion—even infinite loops, such as process message-loops. This means that a function body can be guaranteed to run in O(1) time, since it will have to make a call (either a tail-call or a regular stack call) to continue processing—which allows the scheduler to just reschedule at call-sites, rather than having to preempt functions in the middle of possibly doing something atomic.)
There are two types of function call opcodes in the BEAM VM: local calls, which call a function by offset within the same module they're defined in; and remote calls, which store module and function name symbolically, and pass them off to the code server to dereference.
All you have to do is update which module is referred to by a given symbol in the code server's module table, and then all remote calls to that module will jump to the new module's code instead of the old one's. Since the idiomatic way to define an Erlang process is in terms of a message-loop step function that makes a remote recursive-tail-call to itself at the end, each process will silently "jump into" the newest version of its module code after each message-loop step.
(Possibly more interesting for some of you is the fact that all loops in Erlang are defined in terms of tail-call-optimized recursion—even infinite loops, such as process message-loops. This means that a function body can be guaranteed to run in O(1) time, since it will have to make a call (either a tail-call or a regular stack call) to continue processing—which allows the scheduler to just reschedule at call-sites, rather than having to preempt functions in the middle of possibly doing something atomic.)