Erlang如何接收表达式?

时间:2018-03-15 18:28:33

标签: erlang elixir

  • 为什么接收表达式有时被称为选择性接收?
  • 什么是“保存队列”?
  • 后段如何运作?

2 个答案:

答案 0 :(得分:3)

程序中涉及一个特殊的“保存队列”,当您第一次遇到接收表达式时,您可能会忽略它的存在。

可选地,表达式中可能有一个后续部分使程序稍微复杂化。

接收表达式最好用流程图解释:

receive
  pattern1 -> expressions1;
  pattern2 -> expressions2;
  pattern3 -> expressions3
after
  Time -> expressionsTimeout
end

Erlang receive

答案 1 :(得分:1)

  

为什么接收表达式有时被称为选择性接收?

-module(my).
%-export([test/0, myand/2]).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").

start() ->
    spawn(my, go, []).

go() ->
    receive
        {xyz, X} ->
            io:format("I received X=~w~n", [X])
    end.

在erlang shell中:

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

2> Pid = my:start().                
<0.79.0>

3> Pid ! {hello, world}.
{hello,world}

4> Pid ! {xyz, 10}.     
I received X=10
{xyz,10}

请注意,第一条已发送的消息没有输出,但是已发送第二条消息的输出。接收是有选择性的:它没有收到所有消息,只收到与指定模式匹配的消息。

  

什么是“保存队列”?

-module(my).
%-export([test/0, myand/2]).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").

start() ->
    spawn(my, go, []).

go() ->
    receive
        {xyz, X} ->
            io:format("I received X=~w~n", [X])
    end,
    io:format("What happened to the message that didn't match?"),
    receive 
        Any ->
            io:format("It was saved rather than discarded.~n"),
            io:format("Here it is: ~w~n", [Any])
    end.

在erlang shell中:

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

2> Pid = my:start().    
<0.79.0>

3> Pid ! {hello, world}.
{hello,world}

4> Pid ! {xyz, 10}.     
I received X=10
What happened to the message that didn't match?{xyz,10}
It was saved rather than discarded.
Here it is: {hello,world}
  

后段如何运作?

-module(my).
%-export([test/0, myand/2]).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").

start() ->
    spawn(my, go, []).

go() ->
    receive
        {xyz, X} ->
            io:format("I received X=~w~n", [X])
    after 10000 ->
        io:format("I'm not going to wait all day for a match.  Bye.")
    end.

在erlang shell中:

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

2> Pid = my:start().
<0.79.0>

3> Pid ! {hello, world}.
{hello,world}
I'm not going to wait all day.  Bye.4> 

另一个例子:

-module(my).
%-export([test/0, myand/2]).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").

sleep(X) ->
    receive
    after X * 1000 ->
        io:format("I just slept for ~w seconds.~n", [X])
    end.

在erlang shell中:

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

2> my:sleep(5).                   
I just slept for 5 seconds.
ok