Erlang は初めてで、あるプロセスからプロセスのリストにメッセージを送信する方法を理解しようとしています。
文字列と Pid を含む要素を持つリストを保持するデータ構造があるとします。前に説明した2つの要素の1つであるPidにメッセージ「M」をPidに送信させるにはどうすればよいですか? 私が思いついたのは次のとおりです。
broadcast(P, M, R) ->
P ! {self(), friends},
receive
{P, Friends} ->
P ! {self(), {send_message, {M, R, P, Friends}}}
end.
looper({Name, Friends, Messages}) ->
receive
{From, friends} ->
From ! {self(), Friends},
looper({Name, Friends, Messages});
{From, {send_message, {M, R, ID, [{FriendPid, FriendName} | FriendTale]}}} ->
if R =< 0 ->
From ! {From, {self(), {ID, M}}},
looper({Name, [{FriendPid, FriendName} | FriendTale], [{ID, M} | Messages]});
R > 0 andalso FriendTale =/= []->
FriendPid ! {From, {send_message, {M, R-1, ID, FriendTale}}},
looper({Name, FriendTale, [{ID, M} | Messages]})
end;
terminate ->
ok
end.
しかし、私が理解していることは、Pid のリストの要素から Pid を「抽出」できるように、Pid のリストを正しくパターン一致させていないか、リストを正しく使用してメッセージを送信していないことです。それ。
基本的に、新しいメッセージが到着するのを常に待っている「ルーパー」と呼ばれる機能があります。タイプのメッセージを受信したとき
{send_message, {M, R, ID, [{FriendPid, FriendName} | FriendTale]}}
ここで、「M」は「Friends」と呼ばれる Pid のリストにブロードキャストしたいメッセージであり、R は単なる整数です。
R は基本的に、メッセージがどこまで進むべきかを示す整数です。
e.g. 0 = broadcast the message to self,
1 = broadcast the message to the friends of the pid,
2 = broadcast the message to the friends of the friends of the pid and so on...
Pid をセットアップし、Pid 間の「友情」を設定し、メッセージをブロードキャストした後、端末から得られるものは次のとおりです。
1> f().
ok
2> c(facein).
facein.erl:72: Warning: variable 'From' is unused
{ok,facein}
3> {Message, Pid} = facein:start({"dummy", [], []}).
{ok,<0.186.0>}
4> {Message, Pid2} = facein:start({"dummy2", [], []}).
{ok,<0.188.0>}
5> facein:add_friend(Pid,Pid2).
ok
6> facein:broadcast(Pid,"hello",1).
=ERROR REPORT==== 5-Oct-2014::12:12:58 ===
Error in process <0.186.0> with exit value: {if_clause,[{facein,looper,1,[{file,"facein.erl"},{line,74}]}]}
{<0.177.0>,{send_message,{"hello",1,#Ref<0.0.0.914>}}}
メッセージをブロードキャストした Pid のメッセージを表示すると、コンソールがハングするだけで、他の Pid にはメッセージが受信されません。
どんな助けでも大歓迎です。ありがとう