Erlang code_change和本地函数调用

vbopmzt1  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(156)

我不知道如何在模块中调用 local 函数,以便在代码更改后使用最新版本的代码。请参见以下示例:
要更改的函数是add/1。为了使用最新版本的函数,add/1的调用(第17行)应该是 * 完全限定函数调用 * {Pid, Z} -> Pid ! ?MODULE:add(Z)。当我尝试它时,得到如下结果:

1> c(test). 
{ok,test}
2> test:start(). 
true
3> test:call(1).
2

第22行变更为N + 2

4> c(test).     
{ok,test}
5> test:call(1).
3

第22行再次更改为N + 3

6> c(test).     
{ok,test}
7> test:call(1).
** exception error: bad argument
    in function  test:call/1 (test.erl, line 10)

为什么会出现此错误?

dpiehjr4

dpiehjr41#

I believe that you need to eventually call the fully qualified version of the loop/0 function instead of the add/1 function in order to load and use the new module. The code loading mechanism is prepared to handle two running versions of a module at once, and your example with N+3 is the third load of the module -- and the first versions is forcibly removed.
Try instead this loop:

15 loop() ->
16     receive
17         {Pid, Z} -> Pid ! add(Z)
18     end,
19     ?MODULE:loop().

I've changed it to reload the newest version on next execution of the loop/0 .
I believe more common is to use a reload message or similar that will directly call the main loop explicitly, to avoid the overhead of constantly reloading the module on every request.

相关问题