Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of types can be sent on an Erlang message?

Mainly I want to know if I can send a function in a message in a distributed Erlang setup.

On Machine 1:

F1 = Fun()-> hey end,

gen_server:call(on_other_machine,F1)

On Machine 2:

handler_call(Function,From,State) ->
{reply,Function(),State)

Does it make sense?

like image 968
Federico Avatar asked May 24 '11 13:05

Federico


People also ask

How do I send a message to Erlang?

Erlang uses the exclamation mark (!) as the operator for sending a message. Example: As I have mentioned before, the shell is nothing more than a process. As a process, it has a message queue.

What is an Erlang process?

Erlang is designed for massive concurrency. Erlang processes are lightweight (grow and shrink dynamically) with small memory footprint, fast to create and terminate, and the scheduling overhead is low.

How do I stop Erlang process?

A process can terminate itself by calling one of the BIFs exit(Reason), erlang:error(Reason), erlang:error(Reason, Args), erlang:fault(Reason) or erlang:fault(Reason, Args). The process then terminates with reason Reason for exit/1 or {Reason,Stack} for the others.


1 Answers

Here's an interesting article about "passing fun's to other Erlang nodes". To resume it briefly:

[...] As you might know, Erlang distribution works by sending the binary encoding of terms; and so sending a fun is also essentially done by encoding it using erlang:term_to_binary/1; passing the resulting binary to another node, and then decoding it again using erlang:binary_to_term/1.[...] This is pretty obvious for most data types; but how does it work for function objects?

When you encode a fun, what is encoded is just a reference to the function, not the function implementation. [...]

[...]the definition of the function is not passed along; just exactly enough information to recreate the fun at an other node if the module is there.

[...] If the module containing the fun has not yet been loaded, and the target node is running in interactive mode; then the module is attempted loaded using the regular module loading mechanism (contained in the module error_handler); and then it tries to see if a fun with the given id is available in said module. However, this only happens lazily when you try to apply the function.

[...] If you never attempt to apply the function, then nothing bad happens. The fun can be passed to another node (which has the module/fun in question) and then everybody is happy. Maybe the target node has a module loaded of said name, but perhaps in a different version; which would then be very likely to have a different MD5 checksum, then you get the error badfun if you try to apply it.

I would suggest you to read the whole article, cause it's extremely interesting.

like image 149
Roberto Aloi Avatar answered Sep 27 '22 20:09

Roberto Aloi