Erlang:如何只接收来自特定发件人的消息?

时间:2019-03-17 17:54:48

标签: erlang message-passing

在Erlang中,如何接收从特定pid发送的消息?

2 个答案:

答案 0 :(得分:3)

以下是几种方法:

1)向目标进程发送一个秘密代码,它可以将其所有消息发送回去:

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

worker(TargetPid, Msg, SecretId) ->
     TargetPid ! {Msg, SecretId}.

get_msg(SecretId) ->
    receive
        {Msg, SecretId} -> Msg
    end. 

test() ->
    SecretId = "A1!cd!",
    spawn(my, worker, [self(), hello, "Xy*d1"]),
    spawn(my, worker, [self(), goodbye, SecretId]),

    io:format("~w~n", [get_msg(SecretId)]).

在外壳中:

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

7> my:test().
goodbye
ok

8> 

2)让目标进程发送一条带有其Pid标签的消息,而不是与receive子句中的密码进行匹配:

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

get_msg(TargetPid) ->
    receive
        {Msg, TargetPid} -> Msg
    end. 

worker(TargetPid, Msg) ->
     TargetPid ! {Msg, self()}.

test() ->
    spawn(my, worker, [self(), hello]),
    Pid = spawn(my, worker, [self(), goodbye]),

    io:format("~w~n", [get_msg(Pid)]).

在外壳中:

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

4> my:test().
goodbye
ok

5> 

答案 1 :(得分:2)

您需要在邮件中包含发件人的pid,并在接收过程中将其与之匹配。