Erlang-併發

 

創建新進程:spawn

語法:spawn(Module, Exported_Function, List ofArguments).

舉例:spawn(tut14, say_something, [hello, 3]),

 

發消息:Pid ! Message

舉例:Ping_PID ! pong表示向Ping_PID進程發送元組pong (!操作符用於發消息)

 

self():self() returns the pid of the process which executes self()

 

接收消息:receive ....end

語法:

receive
   pattern1 ->
       actions1;
   pattern2 ->
       actions2;
   ....
   patternN
       actionsN
end.

 

接收超時:after

語法:after time

舉例:after 5000(見tut19)

pong() ->
    receive
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    after 5000 ->
            io:format("Pong timed out~n", [])
    end.

下面兩個特殊的超時time:

1)infinity(無窮大),infinity是一個atom,指定了超時設置將永遠不會被執行。
2) 0,超時如果設定爲0意味着超時設置將立刻執行,但是系統將首先嚐試當前“郵箱”裏的消息。
 

-module(tut14).

-export([start/0, say_something/2]).
say_something(What, 0) ->
    done;
say_something(What, Times) ->
    io:format("~p~n", [What]),
    say_something(What, Times - 1).
start() ->
    spawn(tut14, say_something, [hello, 3]),
    spawn(tut14, say_something, [goodbye, 3]).

 

-module(tut15).
-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(tut15, pong, []),
    spawn(tut15, ping, [3, Pong_PID]).

 

-module(tut19).
-export([start_ping/1, start_pong/0,  ping/2, pong/0]).
ping(0, Pong_Node) ->
    io:format("ping finished~n", []);
ping(N, Pong_Node) ->
    {pong, Pong_Node} ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_Node).
pong() ->
    receive
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    after 5000 ->
            io:format("Pong timed out~n", [])
    end.
start_pong() ->
    register(pong, spawn(tut19, pong, [])).
start_ping(Pong_Node) ->
    spawn(tut19, ping, [3, Pong_Node]).

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章