簡體   English   中英

在Erlang中注冊進程並調用模塊函數

[英]Registering a process and calling a module function in Erlang

我是Erlang的新手。 我有一個Map,必須使用它創建所有鍵的注冊過程,然后進行進一步處理。 我在partone模塊中注冊進程:

-module(partone). 
-import(parttwo,[start/2]).
start() ->
    {ok,List}=file:consult("file.txt"),
    MyMap=maps:from_list(List),
    maps:fold(
        fun(Key,Value,ok) -> 
            print_Map([Key],[Value])
        end,ok,MyMap),
    maps:fold(
        fun(K,V,ok) -> 
            register(K,spawn(calling, startFun,[K,V]))
        end,ok,MyMap).

print_Map(Key,Value)->
    io:fwrite("~n~w : ~w",[Key,Value]).

parttwo.erl:
-module(parttwo).
-export([startFun/2]).
-import(partone,[startFun/0]).

 startFun(Key,Value) ->
    io:fwrite("~w~n KEY::",[Key]).

我可以在print_Map的輸出中獲取地圖內容。 但是然后我得到了以下錯誤:{“初始化在do_boot中終止”,{function_clause,[{交換,'-start / 0-fun-1-',[jill,[bob,joe,bob],true] ,[{文件, “d:/exchange.erl”},{線,40}]},{列表,與foldl,3,[{文件, “lists.erl”},{線,1263}]},{初始化,start_em,1,[{文件, “init.erl”},{線,1085}]},{INIT,do_boot,3,[{文件, “init.erl”},{線,793}]} ]}} init終止於do_boot({function_clause,[{exchange,-start / 0-fun-1-,[jill,[ ],true],[{ },{ }]},{lists,foldl,3, [{ },{_}]},{init,start_em,1,[{ },{ }]},{init,do_boot,3,[{ },{ }]}]}}))

故障轉儲正在寫入:erl_crash.dump ... done

您遇到的問題是由於使用ok作為maps:fold()的第三個參數引起的。

在您對maps:fold()第一次調用中,因為io:fwrite()返回ok ,所以每次調用都會返回ok ,這意味着erlang進行了調用:

Fold_Fun(hello, 10, ok)

符合您的fun子句:

                          |
                          V
Fold_Fun = fun(Key,Value,ok) -> ...

但是,在第二個maps:fold()調用中,因為register()返回一個pid,所以您的樂趣每次調用都會返回一個pid,這意味着erlang進行了調用:

Fold_Fun(hello, 10, SomePid)

與fun子句不匹配:

                        a pid
                          |
                          V
Fold_Fun = fun(Key,Value,ok)

如果要忽略maps:fold()的第三個參數,則可以指定一個無關變量 ,例如_Acc 在erlang中,變量將匹配任何內容,而原子ok將僅匹配ok

====

spawn(calling, startFun,[K,V])

您尚未發布有關“呼叫”模塊的任何信息。

-module(my).
-compile(export_all).

start() ->
    {ok, Tuples} = file:consult("data.txt"),
    MyMap = maps:from_list(Tuples),
    io:format("~p~n", [MyMap]),
    Keys = maps:keys(MyMap),
    lists:foreach(
      fun(Key) -> 
            #{Key := Val} = MyMap,
            register(Key, spawn(my, show, [Key, Val]))
      end,
      Keys
    ).

show(Key, Val) ->
    io:format("~w : ~w~n", [Key, Val]).

data.txt中:

~/erlang_programs$ cat data.txt
{hello, 10}.
{world, 20}.

在外殼中:

9> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}

10> my:start().
#{hello => 10,world => 20}
hello : 10
world : 20
ok

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM