Skip to content

Instantly share code, notes, and snippets.

@lucarin91
Created May 31, 2018 15:46
Show Gist options
  • Save lucarin91/1d74c58b6ec02452b4f0a309ff0659f3 to your computer and use it in GitHub Desktop.
Save lucarin91/1d74c58b6ec02452b4f0a309ff0659f3 to your computer and use it in GitHub Desktop.
A simple example of an Erlang server that can dynamically change the code to process new requests.
-module(hot_change).
-export([start/0, send/1, update_code/1]).
start() ->
F = fun(Str) -> string:lowercase(Str) end,
register(hot_change_server, spawn(fun () -> loop(F) end)).
loop(F) ->
receive
{request, Pid, Q} ->
Res = F(Q),
Pid ! Res,
loop(F);
{update, F1} ->
loop(F1)
end.
send(Q) ->
hot_change_server ! {request, self(), Q},
receive
Res -> Res
end.
update_code(F) -> hot_change_server ! {update, F}, ok.
@lucarin91
Copy link
Author

A possible executing inside erl

1> c(hot_change).
{ok,hot_change}
2> hot_change:start().
true
3> hot_change:send("Hello World!").
"hello world!"
4> hot_change:update_code(fun(Str) -> string:uppercase(Str) end).
ok
5> hot_change:send("Hello World!").
"HELLO WORLD!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment