Erlang并发编程介绍

2019-11-06 09:25:41王冬梅


receive
  {Pid1,Msg} ->

end

通过模式匹配决定只有Pid1进程发送的消息才接受。

3.一些例子
    仅说明下书中计数的进程例子,我添加了简单注释:

-module(counter).
-compile(export_all).
% start(),返回一个新进程,进程执行函数loop
start()->spawn(counter, loop,[0]).
% 调用此操作递增计数
increment(Counter)->
    Counter!increament.
% 返回当前计数值
value(Counter)->
    Counter!{self(),value},
    receive
        {Counter,Value}->
            %返回给调用方
            Value
        end.
  %停止计数     
 stop(Counter)->
     Counter!{self(),stop}.
 loop(Val)->
     receive
         %接受不同的消息,决定返回结果
         increament->
             loop(Val+1);
         {From,value}->
             From!{self(),Val},
             loop(Val);
         stop->
             true;
         %不是以上3种消息,就继续等待
         Other->
             loop(Val)
      end.  


调用方式:

1> Counter1=counter:start().
<0.30.0>
2> counter:value(Counter1).
0
3> counter:increment(Counter1).
increament
4> counter:value(Counter1).
1

基于进程的消息传递机制可以很容易地实现有限状态机(FSM),状态使用函数表示,而事件就是消息。具体不再展开

4.超时设置

    Erlang中的receive语法可以添加一个额外选项:timeout,类似:

receive
   Message1 [when Guard1] ->
     Actions1 ;
   Message2 [when Guard2] ->
     Actions2 ;
  
   after
      TimeOutExpr ->
         ActionsT