Wow…

I had heard about Erlang’s hot code swapping. But never used it so far. Well, I just tried it today, and I am still the bits of my jaw, which dropped while running the following code:

Eshell V5.4.3 (abort with ^G)
1> c(m).
{ok,m}
2> Pid=m:init().
rebooting...
<0.36.0>
3> Pid!{self(),status}.
M/status: tagadax
{<0.29.0>,status}

Here I change the code to return “tagada” [no -x] next time the code is run.

4> c(m).
{ok,m}
5> Pid!{self(),code_switch}.
Requesting reboot...
{<0.29.0>,code_switch}
6> Pid!{self(),status}.
M/status: tagada
{<0.29.0>,status}
7>

And, hang on to your socks, here’s the full code:

-module(m).
-export([init/0,loop/1,message/0]).
message() -> tagada.
init() ->
io:format("rebooting...~n",[]),
spawn(m,loop,[message()]).
loop(M) ->
  receive
    {_, code_switch} ->
      io:format("Requesting reboot...~n",[]),
      m:loop(m:message());
    {Nugu, status} ->
      Nugu ! M,
      io:format("M/status: ~w~n",[M]),
      loop(message())
  end.

m:loop(m:message()); is the full code doing the hot swap. Nice eh? When you do a call to a fully qualified function, MODULE:FUNCTION, the code is hot swapped. That’s it… Amazing!

Erlang

Leave a Reply

You must be logged in to post a comment.