by coldtea · 3y ago · 0 comments
universal_server() ->
receive
{become, F} ->
F()
end.
I mean what purpose does it serve other than having F() directly? One could just directly spawn F on the remote machines, no?(Perhaps that would need to have the code for F already on those remote vms, whereas this eg. also serializes and forwards F's code?)
I would understand the utility if this also handled some common boilerplate, but it seems to just wait for become F message and then doing F().
The way it works is that F is a closure. It contains some code but could have captured variables as well as it’s environment. Calling F() then executes the code and it will have access to the whole surrounding environment when F was created.
In Erlang we can send a closure across the network to another Erlang node. That can be used and is cool but you still need the module code referenced in the closure available on all nodes.
Long story short, in production code you’re right, we would just call the F module directly and pass its the arguments explicitly. This is more of a cool demonstration of possibilities.
For modules, BEAM can have two versions loaded: the current version, and an old version. When you make a fully qualified function call module:function(...), it will call the current version, but calls within the module stay within the same version.
So if you load a module's new beam file, all processes that make fully qualified calls into that module get the new version. In case you're wondering, if you load a third version, any processes that still running in the first version get killed (you can check before you load a third version if you don't want that).
It's idiomatic to write receive loops as
loop(State) ->
NewState = receive ...
end,
?MODULE:loop(NewState).
so that if a new version of the module is loaded, processes will update after they next receive a message. Then you might add a timeout or a heartbeat message to ensure the processes update in a reasonable timeframe. Or use gen_server which has the loop and calls your module so processes only linger in your old module while working on a request.yes.
but you can also send the code to the remote VM
for example in Elixir you can `Code.compile_string` which returns the name of the module and the code as binary (beam bytecode)
You can then send that bytecode to another VM and load it in the remote VM using
:rpc.call('node@remote_host', :code, :load_binary, [the_module_name, "filename_doesnt_really_matter", binary_code])
and then spawn it spawn('node@remote_host', my_module, my_function, [args])