2016-02-24 14 views
4

我是erlang編程的初學者。要了解熱代碼加載好,我從Wikipedia使用的例子(我加入到發送的Pid響應用於調試):Erlang Hot Code加載無法保持狀態

%% A process whose only job is to keep a counter. 
    %% First version 
    -module(counter). 
    -export([start/0, codeswitch/2]). 

    start() -> loop(0). 

    loop(Sum) -> 
    receive 
     {increment, Count} -> 
      loop(Sum+Count); 
     %% modified code, which will be loaded: 
     % reset -> 
     %  loop(0); 
     {counter, Pid} -> 
      Pid ! {counter, Sum}, 
      loop(Sum); 
     {code_switch, Pid} -> 
      Pid ! {switch, Sum}, 
      ?MODULE:codeswitch(Pid, Sum) 
      % Force the use of 'codeswitch/2' from the latest MODULE version 
    end. 

    codeswitch(FromPid, Sum) -> 
     FromPid ! {switched, Sum}, 
     loop(Sum). 

一切都很好。我可以在shell中通過c(counter).加載模塊,通過Pid = spawn(fun counter:start/0).產生一個新進程併發送消息到衍生進程。現在當我通過c(counter).添加一個新的模式來接收表達reset -> loop(0)和重新加載代碼,一切正常,新的代碼加載,Sum保持其增加的值等

但是,當我發送{code_switch, self()}消息,Sum得到當調用loop(Sum)FromPid ! {switched, Sum}中的FromPid ! {switched, Sum}仍然返回正確狀態)時復位爲0。

我錯過了什麼,爲什麼我的狀態在第一次調用codeswitched函數後就消失了?

感謝您的幫助!

| 18 | Pid ! {counter, self()}. 
{counter,<0.49.0>} 
| 19 | flush(). 
Shell got {counter,6} 
ok 
| 20 | Pid ! {code_switch, self()}. 
{code_switch,<0.49.0>} 
| 21 | flush(). 
Shell got {switch,6} 
Shell got {switched,6} 
ok 
| 22 | Pid ! {counter, self()}. 
{counter,<0.49.0>} 
| 23 | flush(). 
Shell got {counter,0} 
ok 

我把io:format("DebugInfo:~p~n", [Sum])作爲第一表達loop。結果是:

12> Pid ! {code_switch, self()}. 
DebugInfo:3 
{code_switch,<0.33.0>} 
DebugInfo:0 
13> flush(). 
Shell got {switch,3} 
Shell got {switched,3} 
ok 

編輯:我發現,當我通過spawn/3,又名spawn(counter, start, []).產卵的過程中,這個工程。當我通過spawn/1產生該過程時,又名spawn(fun counter:start/0),這不是 的工作。這是預期的行爲?我錯過了什麼?對於spawn/1

Documentation狀態:

返回玩轉應用到空列表[]開始一個新的進程的進程標識符。否則就像spawn/3一樣。

編輯: .... Aaaand試圖複製這個Ubuntu的虛擬機上(如果這沒有發生過),我現在還無法重現這種情況(將考驗我的腐敗內存後現在..)

回答

1

這不是測試你的程序的時候,我看到的行爲:

25> LPid ! {counter, self()}. 
{counter,<0.39.0>} 
26> flush(). 
Shell got {counter,6} 
ok 
27> c(counter). 
{ok,counter} 
28> LPid ! {counter, self()}. 
{counter,<0.39.0>} 
29> flush().     
Shell got {counter,6} 
ok 
30> LPid ! {increment, 2}. 
{increment,2} 
31> LPid ! {counter, self()}. 
{counter,<0.39.0>} 
32> flush().     
Shell got {counter,8} 
ok 
33> LPid ! {code_switch, self()}. 
{code_switch,<0.39.0>} 
34> flush().      
Shell got {switch,8} 
Shell got {switched,8} 
ok 
35> LPid ! {counter, self()}.  
{counter,<0.39.0>} 
36> flush().     
Shell got {counter,8} 
ok 

你能也許添加一些日誌像io:format("DebugInfo:~p~n", [Sum]).一些功能,看看這是怎麼回事?

+0

我把'io:format(「DebugInfo:〜p〜n」,[Sum])'作爲'loop'中的第一個表達式。結果依然。當在代碼開關後調用'loop'時,'Sum'爲0 ..(請參閱我的文章以獲取shell輸出。) – tnull

+0

爲了回答您的編輯,我開始了這樣的過程:'start() - > spawn fun() - > loop(0)end).'。最後所有提到的方法都是有效的,這可能是其他方面的問題,而不是你如何開始循環過程。 – Amiramix