我是 Erlang 的新手,我正在尝试了解如何将消息从一个进程发送到进程列表。
假设我们有一个数据结构,其中包含一个包含字符串和 Pid 元素的列表。如何让 Pid 向作为前面描述的两个元素之一的 Pid 发送消息“M”?我想出的是:
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,或者我没有正确使用列表发送消息到它。
基本上,我有一个名为“looper”的函数,它不断等待新消息的到来。当它收到类型的消息时
{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 没有收到任何消息。
任何帮助将不胜感激。谢谢