首页 > 解决方案 > 在 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 的输出中获取地图内容。但后来我收到以下错误: {"init terminating in do_boot",{function_clause,[{exchange,'-start/0-fun-1-',[jill,[bob,joe,bob],true] ,[{file,"d:/exchange.erl"},{line,40}]},{lists,foldl,3,[{file,"lists.erl"},{line,1263}]},{ init,start_em,1,[{file,"init.erl"},{line,1085}]},{init,do_boot,3,[{file,"init.erl"},{line,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

标签: erlangerlang-shell

解决方案


您遇到的问题是由于ok使用maps:fold().

在您第一次调用时maps:fold(),因为io:fwrite()返回ok,您的 funok每次调用时都会返回,这意味着 erlang 进行了调用:

Fold_Fun(hello, 10, ok)

与您的有趣条款相匹配:

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

但是,在您的第二次maps:fold()调用中,因为register()返回一个 pid,所以您的 fun 每次调用时都会返回一个 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]).

数据.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

推荐阅读