跳轉到內容

Erlang 程式設計/程序

來自 Wikibooks,開放的書籍,開放的世界

Erlang 程序和訊息

[編輯 | 編輯原始碼]

在 Erlang 中,建立和控制程序非常容易。

程式 chain_hello.erl 構建了一個任意長度的程序鏈。每個程序建立一個程序,然後向其傳送訊息。該程式建立一個包含 N 個程序的鏈,每個程序輸出 "hello world!<N>"(其中 <N> 是某個整數)。

程序彼此傳送和接收訊息。訊息使用模式匹配讀取。訊息以 FIFO(先進先出)的方式匹配。

注意 1:最終輸出的順序取決於程序排程。

注意 2:時間向下流動(在每條垂直線上,參見注意 1)。

這是執行 chain_hello:start(1) 的程序訊息圖。

start(1)
   |
spawns -----------> listen(1)
   |                   |
   |                spawns --------------------> listen(0)
   |                   |                            |
   |                sends ----> speak ----------> prints --> "hello world 0"
   |                   |                            |
 sends --> speak --> prints --> "hello world 1"     |
                       |                            |
                       ok                           ok

程式清單:chain_hello.erl

-module(chain_hello). 
-compile(export_all).
                                                            %
start(N)->                                                  % startup
       Pid1 = spawn(chain_hello, listen, [N]),
       Pid1 ! speak,
       io:format("done \n").
                                                            %
listen(0)->                                                 % base case
       receive
                speak ->
                       io:format("hello world!~w\n", [0])
       end;
listen(N)->                                                 % recursive case
       Pid2 = spawn(chain_hello, listen, [N-1]),
       Pid2 ! speak,
       receive
               speak ->
                       io:format("hello world!~w\n", [N])
       end.
% ---- sample output ---- %
%
% 14> chain_hello:start(4).
% done
% hello world!4
% hello world!3
% hello world!2
% okhello world!1
% hello world!0
華夏公益教科書