【发布时间】:2014-11-29 13:04:12
【问题描述】:
我是 Erlang 的新手,我正在尝试了解如何将消息从一个进程发送到进程列表。
假设我们有一个包含 Pid 列表的数据结构。如何让 Pid 向 Pid 列表发送消息“M”,其中列表的每个元素都有 2 个元素:字符串(代表名称)和 Pid? 我想出的是:
broadcast(P, M, R) ->
P ! {self(), friends},
receive
{P, Friends} ->
P ! {self(), {send_message, {M, R, P, Friends}}}
end.
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({"Bjarki", [], []}).
{ok,<0.186.0>}
4> {Message, Pid2} = facein:start({"Bjarki2", [], []}).
{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>}}}
任何帮助将不胜感激。 谢谢
【问题讨论】:
-
您能否添加
loop定义(您的论点如何准确命名)。 -
@mpm ok 添加了looper定义
-
您可以考虑使用gproc,它有一个方便的Pub/Sub module,可以让您订阅一个事件的进程,然后向该事件的所有订阅者发布消息。
标签: erlang erlang-shell