有没有办法在 erlang 中向远程节点发送闭包?
Is there a way to send a closure to remote node in erlang?
它接缝 erlang 只发送有趣的引用到远程节点。当尝试发送闭包时,它显然在调用模块中内联闭包,并将一个有趣的引用发送到远程节点的内联乐趣。这是测试:
-module(funserver).
-compile(export_all).
loop()->
receive {From, ping} ->
error_logger:info_msg("received ping from ~p~n", [From]),
From ! pong,
loop();
{From, Fun} when is_function(Fun) ->
error_logger:info_msg("executing function ~p received from ~p~n", [Fun, From]),
From ! Fun(),
loop();
M ->
error_logger:error_msg("received ~p, don't know what to do with it", [M])
end.
和客户端节点上的测试:
test_remote_node_can_execute_sent_clojure()->
{ok, ModName, Binary} = compile:file(funserver, [verbose,report_errors,report_warnings, binary]),
{module, ModName} = rpc:call(?other_node, code, load_binary, [ModName, atom_to_list(ModName), Binary]),
Pid = spawn(?other_node, funserver, loop, []),
OutVar = {"token with love from", node()},
Pid ! {self(), fun()-> {OutVar, erlang:node()} end},
receive Result ->
Result = {OutVar, node(Pid)}
after 300 ->
timeout
end.
得到
Error in process <7162.123.0> on node servas@sharas with exit value:
{undef,[{#Fun<tests.1.127565388>,[],[]},
{funserver,loop,0,[{file,"funserver.erl"},{line,12}]}]}
timeout
那么clojure可以发到远程节点吗?
您的示例的问题是客户端节点编译 funserver
模块并将其发送到远程节点 - 但该模块已经存在并正在执行,等待接收消息 - 但它没有发送 tests
模块,该模块实际上包含您发送的乐趣。
在 compile:file
行中,将 funserver
更改为 tests
,它应该可以工作。
此外,您可以使用 code:get_object_code
而不是 compile:file
,因为该模块已经编译并加载到本地节点中。
它接缝 erlang 只发送有趣的引用到远程节点。当尝试发送闭包时,它显然在调用模块中内联闭包,并将一个有趣的引用发送到远程节点的内联乐趣。这是测试:
-module(funserver).
-compile(export_all).
loop()->
receive {From, ping} ->
error_logger:info_msg("received ping from ~p~n", [From]),
From ! pong,
loop();
{From, Fun} when is_function(Fun) ->
error_logger:info_msg("executing function ~p received from ~p~n", [Fun, From]),
From ! Fun(),
loop();
M ->
error_logger:error_msg("received ~p, don't know what to do with it", [M])
end.
和客户端节点上的测试:
test_remote_node_can_execute_sent_clojure()->
{ok, ModName, Binary} = compile:file(funserver, [verbose,report_errors,report_warnings, binary]),
{module, ModName} = rpc:call(?other_node, code, load_binary, [ModName, atom_to_list(ModName), Binary]),
Pid = spawn(?other_node, funserver, loop, []),
OutVar = {"token with love from", node()},
Pid ! {self(), fun()-> {OutVar, erlang:node()} end},
receive Result ->
Result = {OutVar, node(Pid)}
after 300 ->
timeout
end.
得到
Error in process <7162.123.0> on node servas@sharas with exit value:
{undef,[{#Fun<tests.1.127565388>,[],[]},
{funserver,loop,0,[{file,"funserver.erl"},{line,12}]}]}
timeout
那么clojure可以发到远程节点吗?
您的示例的问题是客户端节点编译 funserver
模块并将其发送到远程节点 - 但该模块已经存在并正在执行,等待接收消息 - 但它没有发送 tests
模块,该模块实际上包含您发送的乐趣。
在 compile:file
行中,将 funserver
更改为 tests
,它应该可以工作。
此外,您可以使用 code:get_object_code
而不是 compile:file
,因为该模块已经编译并加载到本地节点中。