主要是我想知道是否可以在分布式Erlang设置中的消息中发送函数。
在计算机1上:
F1 = Fun()-> hey end,
gen_server:call(on_other_machine,F1)
在计算机2上:
handler_call(Function,From,State) ->
{reply,Function(),State)
是否有意义?
最佳答案
Here的有趣文章,涉及“将乐趣传递给其他Erlang节点”。要简短地恢复它,请执行以下操作:
[...] 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.
我建议您阅读整篇文章,因为它非常有趣。
关于erlang - 可以在Erlang消息上发送哪种类型的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6111170/