Erlang多线程相关

来源:互联网 发布:type c数据接口 编辑:程序博客网 时间:2024/06/13 05:44

the term "process" is usually used when the threads of execution share no data with each other and the term "thread" when they share data in some way. Threads of execution in Erlang share no data, that's why we call them processes.


The receive construct is used to allow processes to wait for messages from other processes. It has the format:

receive
   pattern1 ->
       actions1;
   pattern2 ->
       actions2;
   ....
   patternN
       actionsN
end.
Note: no ";" before the end.


Messages between Erlang processes are simply valid Erlang terms. I.e. they can be lists, tuples, integers, atoms, pids etc.


Each process has its own input queue for messages it receives. New messages received are put at the end of the queue. When a process executes a receive, the first message in the queue is matched against the first pattern in the receive, if this matches, the message is removed from the queue and the actions corresponding to the the pattern are executed.


However, if the first pattern does not match, the second pattern is tested, if this matches the message is removed from the queue and the actions corresponding to the second pattern are executed. If the second pattern does not match the third is tried and so on until there are no more pattern to test. If there are no more patterns to test, the first message is kept in the queue and we try the second message instead. If this matches any pattern, the appropriate actions are executed and the second message is removed from the queue (keeping the first message and any other messages in the queue). If the second message does not match we try the third message and so on until we reach the end of the queue. If we reach the end of the queue, the process blocks (stops execution) and waits until a new message is received and this procedure is repeated.


Note how the operator "!" is used to send messages. The syntax of "!" is:


Pid ! Message


I.e. Message (any Erlang term) is sent to the process with identity Pid.


example follows :

-module(tut2).
-export([start/0, ping/2, pong/0]).


ping( 0, Pong_Pid ) ->
    Pong_Pid ! finished,
    io:format("ping finished~n", [] );


ping( N, Pong_Pid ) ->
    Pong_Pid ! { ping, self() },
    receive
       pong ->
          io:format("Ping received pong~n", [] )
    end,
    ping( N-1, Pong_Pid ).


pong() ->
    receive
       finished ->
           io:format("Pong finished~n", [] );
       {ping, Ping_Pid } ->
           io:format("Pong received ping~n", [] ),
           Ping_Pid ! pong,
           pong()
     end.


start() ->
     Pong_Pid = spawn( tut2, pong, [] ),
     spawn( tut2, ping, [3,Pong_Pid] ).


result : 

9> c(tut2).
{ok,tut2}
10> tut2:start().
Pong received ping
Ping received pong
<0.63.0>
Pong received ping
Ping received pong
Pong received ping
Ping received pong
ping finished
Pong finished

原创粉丝点击