3 ms·
If you’re wondering: Erlang (and so Elixir) has a very “pragmatic” design behind its abstract machine/runtime; it’s not like the lack of loops is to be function
by derefr 8y ago
If you’re wondering: Erlang (and so Elixir) has a very “pragmatic” design behind its abstract machine/runtime; it’s not like the lack of loops is to be functionally pure or anything.
They remove loops in the Erlang abstract machine so that there are only ever O(1) instructions executed between each function call (where a tail-recursion is considered a function call.) With this constraint in place, the runtime can get away with a hybrid of cooperative and preemptive scheduling called “reduction scheduling”, where functions only ever yield when they make a function call (or return from one.)
By ensuring every function body has O(1) “reductions” before it hits a CALL or RET op, the runtime guarantees (unlike cooperative scheduling) that execution will always yield from a task in a bounded amount of time; and by ensuring yields only happen at call-sites, the runtime ensures that (unlike preemptive scheduling) there is no register state to preserve at time of yield—all the scheduler has to record when it pauses a task is the thunk (function pointer + parameter list) for the call it was about to make.
Together, these guarantees allow for extremely low-overhead context switching between tasks in a soft-realtime context.
Other systems (e.g. .NET’s Orleans) simulate this hybrid approach by splitting code into state machines with explicit yield points being the state transitions. But AFAIK, only ERTS takes the approach of making function calls into the state transitions. (Because, without the no-native-loops constraint, such an approach doesn’t work at all.)