我的雲端生活網 - Life+

Showing posts with label Erlang. Show all posts
Showing posts with label Erlang. Show all posts

Monday, December 28, 2009

Erlang 叫用外部程式很簡單

多行程程式是 Erlang 語言的一項重要特色。而許多時候需要叫用外部程式, Erlang 的程式寫法也表現得很優秀。

由於標榜 Concurrency-Oriented Programming , Erlang 讓開發者將每一個函數視為行程。行程要與其他行程溝通,必須藉由拋接訊息來表示請求或回應。 Erlang 程式的訊息介面與 ! (send) 和 receive 兩個關鍵字有關。而外部程式的訊息介面,則稱為 port 。 Erlang 對 port 送訊息給外部程式,也從 port 接收外部程式來的訊息。 Erlang 的 open_port/2 提供了外部程式叫用的功能,並且提供了外部程式的 port 設定方式。例如:

Port1 = open_port( {spawn, simple_work}, [in, out, use_stdio] )

以上 port 的選項, in 容許 simple_work 外部程式可以從 port 接受輸入訊息, out 容許外部程式可以從 port 輸出訊息, use_stdio 指定外部程式的標準輸入和輸出分別對應為 port 輸入和 port 輸出。 simple_work 可能是以下 perl 程式:

#!/usr/bin/perl -w
# simple_work program
my $buffer;
$buffer = readline STDIN;
print $buffer

Erlang port_command/2 可以指定 port 並送訊息。例如:

port_command(Port1, "hello!\n")

simple_work 送出 port 的訊息, Erlang 程式要用 receive 接受訊息,收到的訊息格式依 open_port/2 的選項決定。

參考資料

Friday, November 6, 2009

邏輯程式設計 Prolog

最近花不少時間重新看 Prolog 和 Erlang 的程式寫法,感想是,邏輯程式工具的威力真強。

Prolog 是一種老派的邏輯式程式語言,它的目標是執行邏輯系統。邏輯系統是一些事實和一些規則組成的一組「資料庫」,在系統定義範圍內,可以找到有一些情況被滿足。例如最簡單的三段論法說:

morale(X) :- man(X).
man(socrates).

?- man(socrates).
yes
?- man(me).
no

以上程式中,大寫符號是變數,小寫符號是常在詞彙。句子呈現 X :- Y 是規則,讀做 X if Y ,在邏輯表達式是寫成 X <- Y 。另一種普通的句子是事實。而末尾有 ?- 開頭的,是查詢句。根據以上程式,有些對邏輯一知半解的會大叫:「喔!原來我不道德!」但只是因為以上的三段論與現實的認知稍有差別:邏輯句子表達的是語意的最基本部份,但是日常用語的語意結構非常複雜。

Prolog 程式只要定義幾個句子,執行器就會找出一些滿足這些句子的情況。邏輯推論也是如此。設想有個句子定義可以從一列資料的某個位置取出一項資料:

element_at([X|_], 1, X).
element_at([_|Y], N, Z) :- element_at(Y, N1, Z), N is N1 + 1.

第一句說,對開頭為X的一列資料取第一項,答案是X。第二句則使用了遞迴定義。 (第二句讀作:(右邊) 如果 Y 的第 N1 位置是 Z ,則 (左邊) Y 前面多一項資料,這一列的第 N 位置是 Z 。) 以這樣的寫法,除了可以從一列裏指定位置取得資料之外:

?- element_at([a,b,c,d,e], 2, X).
X = b

還可以查詢在什麼位置可以找到指定的資料:

?- element_at([a,b,b,c], N, b).
N = 2;
N = 3

程式的評估,基本上是反覆檢查可以成立的句子,於是可以將所有的情況一筆一筆找出來。所以,寫一些列出各種情況的程式就變得很簡單。例如,寫個組合程式:

combination(0, _, []).
combination(_, [], []).
combination(1, X, [Z]) :- element_at(X, _, Z).
combination(N, [X|Y], [X|Z]) :- N > 1, N1 is N - 1, combination(N1, Y, Z).
combination(N, [_|Y], Z) :- N > 1, combination(N, Y, Z), length(Z, N).

第四句只考慮一列的第一個元素X參與在答案中的情況,而第五句純粹考慮第一個元素不參與在答案中的情況。 (第四句讀作: (右邊) 如果對 Y 取 N1 個元素的一種組合是 Z ,則 (左邊) 對 Y 前面加了一項 X ,取 N 個元素的一種組合,就是 Z 前面也加 X 。因果關係!) 寫程式時,考慮答案只考慮各種情況的其中一種,但程式執行時, Prolog 就像內建迴圈機能一樣,反複將各種情況一樣接著一樣列出來:

?- combination(3, [a,b,c,d,e], X).
X = [a,b,c];
X = [a,b,d];
X = [a,b,e];
X = [a,c,d];
X = [a,c,e];
......

跟 Erlang 比較, Erlang 程式沒有反覆測試每一條句子的執行方式,因為 Erlang 是函數式語言,函數的特性是從多個輸入也必須只對應到一個值。不過, Erlang 也是經由長期用 Prolog 慢慢開發完成的。這是我拿 Prolog 和 Erlang 對照檢視的原因。

Erlang 的組合程式:

combination(0, _) -> [[]];
combination(_, []) -> [[]];
combination(1, X) -> [ [Z] || Z <- X ];
combination(N, [X|Y]) -> [ [X|Z] || Z <- combination(N-1, Y) ] ++
[ Z || Z <-combination(N, Y), length(Z) == N ].

(第四句讀作: (左邊) 想求得 Y 列前面有個 X 的資料取 N 個元素的各種組合情況,先求 (右邊) 可能是對 Y 求 N-1 個元素的各種組合情況,再將 X 套到每個組合情況之前,或者是直接求 Y 中取 N 個元素的各種組合情況。至於末尾檢查 length(Z) == N ,是要克服後半程式結果的不一致情形。)

執行結果:

> test:combination(3, [a,b,c,d,e]).
[[a,b,c],
[a,b,d],
[a,b,e],
[a,c,d],
[a,c,e],
[a,d,e],
[b,c,d],
[b,c,e],
[b,d,e],
[c,d,e]]

Erlang 缺乏逐步列出各種情況的機能,所以要列出全部的組合情況,用 Erlang 必須把各種答案都算出來,並收集成一列。寫 Erlang 程式顯然比寫 Prolog 程式更辛苦一點點,不過, Erlang 提供 List Comprehension 表達法,使這個組合程式也變得稍微簡單一點點。

Tuesday, November 3, 2009

用Erlang做個文書編輯器

11月1日在Erlang Programming論壇發起一陣討論,談到用Erlang寫文字編輯器的疑問(見1.) 。Ted問到,據說Erlang是分散處理及容錯都很好的語言,那麼如果寫文字編輯器,有什麼並行方面的好處?Mats說,如果有分散處理能力,很好,他常在寫東西到一半必須把半成品備份,這樣可以保留他許多編輯的狀態。

Jayson回答,Erlang雖然不錯,但是講到字串處理真是麻煩透了。倒不如使用JRuby或Clojure之類,建立在Java基礎上的語言。接著,Erlang的發明人Joe答覆了,他指出Erlang做列式的資料處理真是超快的。文字編輯器所需要的文字處理,那些在C++看成string的東西,在Erlang只要把它看成list就做得很棒了。他還說,用C寫文字編輯器才是痛苦的事。最麻煩的undo功能,C語言寫起來要擔心stack中儲存的狀態有沒有改掉,而用Erlang做起來很簡單,因為語言特性比較少有狀態改變。

另外,對於載入及搜尋大檔案方面,Joe指出如果你不會寫大檔案處理的功能,這不是語言方面有問題,而是你缺少演算法的知識。他曾經需要處理gigabytes的檔案,讀過 "Managing Gigabytes" 一書之後,實作了gamma encoding就解決了問題。

Luke Gorrie有個用Erlang寫的仿Emacs。(見2.)

1. Erlang for Programming a Text Editor, discussions from Erlang Programming group at Google groups, url: http://groups.google.com/group/erlang-programming/browse_thread/thread/a6c93367b439a284?hl=en .
2. Luke Gorrie, Ermacs (software), http://fresh.homeunix.net/~luke/ermacs/ .

Thursday, June 11, 2009

(翻譯) Erlang 程式設計第七章:並行風格

Joe Armstrong 在 Erlang Programming 書中有一段提到「平行程式設計」 (Concurrent-oriented programming, COP) 的概念。以下翻譯那一段文章,提供許多人即使在用非平行程式設計方式開發平行系統架構時,也可以引用這些概念。



並行風格

人都知道何謂並行 對並行的深入認知,直接連通到我們腦內。我們能極速地對刺激做反射動作,是用到腦的一部份,稱為杏仁體。若少了這樣的反應,我們可能會死。有意識的思考動作太慢。而用到思考「快拉煞車桿」耗掉的時間,我們早就做了那個動作了。

行駛在幹道上的時候,我們心裡會打量十幾輛或百來輛車。這不經過意識思考。如果我們沒本事做到這種事,可能就會死。

世界是平行的 假如我們要寫一些程式,表現如同在真正世界中表現著的其他物件,這些程式會有個並行的組織方式。這是何以我們該用「並行程式語言」來寫程式。

然而我們很常用「循序程式語言」寫真實世界的程式。真是多餘的難。

用我們設計來寫並行應用程式的語言吧!並行程式開發會變得超容易。

Erlang 程式建構我們思考及感興趣的模型 我們不共用記憶。我有我的記憶,你有你的記憶。咱們是兩個腦袋,一人一個。兩個腦袋不會融合成一個。要改變你的記憶,我要對你送訊息,或者說,我要揮揮手。你聽到了,或瞧見了,你的記憶就會改變。不過,如果沒問你問題並看看你的反應,我不知道你有沒有收到我的訊息。

這是有 Erlang 程序的情況該是的樣子。 Erlang 程序沒有共用記憶體,每個程序有自己的記憶體。要改變其他程序的記憶體,你必須送個訊息,期望對方收到並了解訊息。要確定別的程序已經收到你的訊息,並且改變他的記憶體了,你必須問問他 (也送個訊息) 。這完全是我們都怎麼互動的模式。

煦:嗨,比爾,我的電話號碼是 45-67-89-12 。
煦:你聽到了嗎?
比爾:有,你的號碼是 45-67-89-12 。

這些互動模式是我們如此熟悉,從小到大我們都和這世界這樣互動,觀察它,對它送送訊息,然後看看反應。

人們發揮功用,如獨立個體般送訊息做溝通 這是 Erlang 程式做事的辦法,也是人們做事的辦法。所以,很容易學懂一份 Erlang 程式。

一份 Erlang 程式用許多成千或上百千的小程序構成。這些小程序獨立運作。它們彼此送訊息溝通。每個程序有自己的記憶體。它們表現得像一大房間的人群彼此在饒舌交談。

這讓 Erlang 天生就是簡單,容易維護並擴充。假定我們有十個人 (或程序) ,他們要做太多工作。可以怎麼做呢?找更多人來。而我們怎麼管理這些人呢?很簡單,就對他們喊口令 (或叫廣播) 。

Erlang 程序沒有共用記憶體,所以記憶體使用時不需要鎖定。有鎖的地方就有會有鑰匙,而有鑰匙就可能會遺失鑰匙。當你鑰匙掉了會怎麼樣呢?你會驚慌得不知道怎麼辦。在軟體發生的,則是當你丟掉了鑰匙,鎖定就造成錯誤。分散式軟體系統如果有鑰匙和鎖,都會出錯。

而 Erlang 可沒有鎖和鑰匙。

有人死掉,其他人一定會注意到 假如我在一個房間裏突然傾覆而死,有人可能會注意到。 Erlang 程序就像人們,他們有時可能死掉。但不像人們的是,人們死掉會用盡力氣叫出聲,而叫聲與他們的死因有關。

想想滿滿一整房間的人,有人突然倒斃了。像他們死的時候,會叫說「我的心臟──我要死了」或是「我的胃抽搐」。這就是 Erlang 程序所做的。一條程序可能死前說:「我死於除以零。」另一條程序可能說:「我死於向空串列要最後一項串列資料。」

現在在我們滿是人的房間裏,假想有位特定的仁兄,他的任務是清除遺體。假定有珍和尚二人,如果珍死掉,尚會修正對珍的死亡所有的錯誤。如果尚死亡,珍會修定那些錯誤。珍和尚是被無形的契約連成一體,約定若有一方死亡,另一方會修正所有造成其死亡的錯誤。

這就是 Erlang 怎麼處理錯誤偵測的方法。程序可以連成一體。如果一條程序死掉,另一條程序獲得一則錯誤訊息,指出前一條程序為什麼死掉。

基本是這樣。 Erlang 怎麼做事如以上所述。

現在我們學到的東西有:
  1. Erlang 程式由一大堆程序構成。這些程序可以彼此送訊息。
  2. 這些程序可能會接收訊息並瞭解訊息,也可能不會。如果你要知道訊息有沒有收到並解讀,你必須向程序送訊息,並等它回應。
  3. 成對的程序可以被連成一體。如果其中之一死掉,錯誤訊息會送給另一個程序,訊息中包含前一程序為什麼死掉的理由。
這種簡單的程式設計模型,是我稱為「並行程式設計」 (COP, Concurrency-Oriented Programming) 的模型一部份。

下一章我們開始寫並行程式。我們需要學三種基本項: spawn 、 send (這用到 ! 運算子) 和 receive 。然後寫一點簡單的並行程式。

當程序死掉的時候,如果有其他程序跟它連成一體,其他程序就會注意到。這是第九章的主題,「並行程式的錯誤」。

在你讀下兩章的時候,想著房間裏有一群人。人們是程序。在房間裏的人們有自己私有記憶,這記憶就是程序的狀態。要改變你的記憶,我就跟你講話,而你就聽,這是送訊息和收訊息。我們會有兒女,這是 spawn (生產) 。我們死掉,就是一條程序結束了。

Sunday, December 16, 2007

Concurrent Programming II

1.Concurrency is easy…?

( http://armstrongonsoftware.blogspot.com/2006/08/concurrency-is-easy.html )


2.Sequential Programming

-module(factorial).
-export([factoriala/1, factorialb/1, factorialc/1, factoriald/1]).


%Simplest:
factoriala(0) -> 1;
factoriala(N) -> N * factoriala(N - 1).


%Using function guards:
factorialb(0) -> 1;
factorialb(N) when N > 0 -> N * factorialb(N - 1).


%Using if:
factorialc(N) ->
if
N == 0 -> 1;
N > 0 -> N * factorialc(N - 1)
end.


%Using case:
factoriald(N) ->
case N of
0 -> 1;
N when N > 0 -> N * factoriald(N - 1)
end.



-module(set).
-export([new/0, add_element/2, del_element/2,is_element/2, is_empty/1, union/2, intersection/2]).

new() -> [].

is_element(H, [H|_]) -> true;
is_element(H, [_|Set]) -> is_element(H, Set);
is_element(_, []) -> false.


is_empty([]) -> true;
is_empty(_) -> false

add_element(X, Set) ->
case is_element(X, Set) of
true -> Set;
false -> [X|Set]
end.


del_element(X, [X|T]) -> T;
del_element(X, [Y|T]) -> [Y|del_element(X,T)];
del_element(_, []) -> [].


union([H|T], Set) -> union(T, add_element(H, Set));
union([], Set) -> Set.


intersection(S1, S2) -> intersection(S1, S2, []).
intersection([], _, S) -> S;
intersection([H|T], S1, S) ->
case is_element(H,S1) of
true -> intersection(T, S1, [H|S]);
false -> intersection(T, S1, S)
end.


3.concurrent programming

Processes and communication between processes are fundamental concepts in Erlang.

1. Process Create

Pid = spawn(Module, FunctionName, ArgumentList)

2. Inter-process Communication

Pid ! Message

receive
Message1 [when Guard1] ->Actions1 ;
Message2 [when Guard2] ->Actions2 ;
_AnyMessage -> Actions3 ;
after Timeout ->Action4
...
end.

3.Receiving messages from a specific process

Pid ! {self(),abc}

receive
{Pid,Msg} ->
...
end


4. Examples

a)
-module(cfac).
-export([start/0,loop/0]).
-import(factorial,[factoriala/1]).

start() ->spawn(counter, loop, []).

loop() ->
receive
{fac,Val}-> io:format("(from:~p)fac ~p=~p ~n",[node(),Val,
factoriala(Val)]),loop();
{exit}->io:format("end~n",[]);
_->loop()
end.


b) performance testing


c) programming with socket
-module(geturl).
-export([start/2,senddata/1,dataarrive/1,startN/3]).
-define(TCP_OPTIONS,[list, {packet, 0}, {active, false}, {reuseaddr,
true}]).

start(Url,Port)->
case gen_tcp:connect(Url,Port ,?TCP_OPTIONS ) of
{ok,CSocket}->geturl:senddata(CSocket);
{error,Why}->Why
end.

senddata(Socket)->
Data="GET / HTTP/1.0\r\nConnection: close\r\nCache-Control:
no-cache\r\n\r\n",
io:format("~p~n",[Socket]),

case gen_tcp:send(Socket,Data) of
ok->io:format("send:~p~n",[Data]),dataarrive(Socket);
{error, Why}->io:format("send_socket close:~p~n",[Why])
end.

dataarrive(Socket)->
case gen_tcp:recv(Socket, 0) of
{ ok, Data} ->io:format("receive:~p~n",[Data]),
dataarrive(Socket);
{error, Why} ->io:format("dataarrive_socket
close:~p~n",[Why])
end.

startN(_,_,0)->io:format("~p~n",["end"]);
startN(Url,Port,Num)->spawn(geturl,start,[Url,Port]),
startN(Url,Port,Num-1).


d) Distributes Programming

erl –sname local
erl –sname remote

Pid=rpc:call(remote@se6,cfac,start,[]).
Pid ! {fac,10}.



5.References

[1] J. Armstrong, R. Virding, C. Wikstr¨om, and M. Williams. Concurrent Programming in Erlang.
[2] J. Armstrong.Erlang Programming.

Wednesday, December 5, 2007

Erlang/OTP R12B released

Major relese : otp_src_R12B-0
Build date : 2007-12-04

R12B-0 is a major new release of Erlang/OTP.
You can download the full source distribution from

http://www.erlang.org/download/otp_src_R12B-0.tar.gz
http://www.erlang.org/download/otp_src_R12B-0.readme (this file)

Note: To unpack the TAR archive you need a GNU TAR compatible program.

For installation instructions please read the README that is part of
the distribution.

The Windows binary distribution can be downloaded from

http://www.erlang.org/download/otp_win32_R12B-0.exe
On-line documentation can be found at http://www.erlang.org/doc/.
You can also download the complete HTML documentation or the Unix manual files

http://www.erlang.org/download/otp_doc_html_R12B-0.tar.gz
http://www.erlang.org/download/otp_doc_man_R12B-0.tar.gz

We also want to thank those that sent us patches, suggestions and bug
reports,

Friday, November 30, 2007

RFID智慧型護送系統建置計畫

昨天接獲資訊:
微程式資訊以專業技術與成功建置經驗獲得經濟部大型示範性計畫『RFID智慧型護送系統建置計畫』的支持,為醫療領域結合IT科技再跨出一步。 這可是一個將近兩千萬的專案阿,不過這事實上是一個XMPP 的應用,我們在XMPP 建置了一些訊息的交換邏輯,讓訊息在XMPP 上交易所產生的應用,業界這幾年對concurrent programming 需求殷切,主要是因為資訊系統跳了一個層次在看訊息傳遞這回事,當大量資訊需要即時 精確的被傳遞時,過去的那種multiprocess mutithread 不敷使用,一個動輒上萬的長時間連線交易,更需要像erlang 這類以concurrent programming 為觀點出發的語言,而這也同時是我會接觸functional language的主要原因

計畫相關聯結:
http://www.program.com.tw/news/news_071129.htm
http://blog.sina.com.tw/sandychang/article.php?pbgid=40436&entryid=575124

Tuesday, November 20, 2007

erlang 相關paper

http://www.it.uu.se/research/group/hipe/publications.shtml

內有相關於erlang 的論文 期刊 或是相關會議裡 提出的文章,其中這兩篇恰好是談到昨天提到的erlang bit syntax

http://user.it.uu.se/~kostis/Papers/JFP_06.pdf
Per Gustafsson and Konstantinos Sagonas
Efficient manipulation of binary data using pattern matching
In the Journal of Functional Programming, 16(1):35-74, January 2006

http://www.it.uu.se/research/group/hipe/papers/padl07.pdf
Per Gustafsson and Konstantinos Sagonas
Applications, Implementation and Performance Evaluation of Bit Stream Programming in Erlang In Proceedings of the Ninth International Symposium on Practical Aspects of Declarative Languages (PADL'07). To appear.

Monday, November 19, 2007

Erlang Bit Syntax

Erlang Bit Syntax 看起來蠻強悍的,在erlang programming 裡提到一個 16-bit Colors 的例子:
<<這例子來自 erlang programming>>
1> Red = 2.
2
2> Green = 61.
61
3> Blue = 20.
20
4> Mem = <<Red:5, Green:6, Blue:5>>.

用在pattern matching也很直觀,比如:

<<Header2:8/binary,$\ ,Rest2/binary>> = <<"HTTP/1.1 200 OK\r\n">>.

不過;他目前還不支援regexp , 用起來有時會綁手綁腳,可能是還不太熟析? Bit Syntax 可以用在網路的封包解析,或是encode/decode某種檔案格式...目前;關於封包分析部分我也還在努力搞懂中

http://community.livejournal.com/en_dmitriid/5806.html

http://www.erlang.se/euc/07/papers/1700Gustafsson.pdf
這裡也有相關Erlang Bit Syntax的文章可參考


Thursday, November 15, 2007

EUC '07 papers and slides

The EUC(Erlang/OTP User Conference 2007) papers and presentations are now available at http://www.erlang.se/euc/07

Tuesday, November 13, 2007

Erlang Cookbook

Erlang Cookbook (裡面有一些不錯的範例),不過建議先讀完erlang 相關的書籍或是線上手冊再來讀會比較有感覺

http://schemecookbook.org/Erlang/TOC

Wednesday, October 31, 2007

erlang 幾個可參考的網站

http://www.planeterlang.org/
http://www.blogjava.net/killme2008/category/20770.html
http://erlang-china.org/

Monday, October 8, 2007

Quicksort in Erlang using two list comprehensions

qsort([]) -> [];
qsort([PivotT]) ->
qsort([X X <- T, X <>= Pivot]).

===以上資料是錯誤的======

qsort([]) -> [];
qsort([Pivot|T]) ->
qsort([X||X<-T,X =< Pivot]) ++
[Pivot] ++
qsort([X||X<-T,X > Pivot]).

Monday, September 24, 2007

Quicksort in Erlang

-module(sort).
-export([sort/1]).

sort([]) -> [];
sort([PivotRest]) ->
{Smaller, Bigger} = split(Pivot, Rest),
lists:append(sort(Smaller), [Pivotsort(Bigger)]).

split(Pivot, L) ->
split(Pivot, L, [], []).
split(Pivot, [], Smaller, Bigger) ->
{Smaller, Bigger};
split(Pivot, [HdTl], Smaller, Bigger) when Hd <>
split(Pivot, Tl, [HdSmaller], Bigger);
split(Pivot, [HdTl], Smaller, Bigger) when Hd >= Pivot ->
split(Pivot, T, Smaller, [HdBigger]).

Monday, September 17, 2007

Sunday, August 12, 2007

erlang 會成為下一個java ?

erlang 會成為下一個java ?
文章連結

其實應該說是functional language 的時代快來臨了,或是已經來臨
文章連結1
文章連結2
文章連結3

Erlang-China
http://www.erlang-china.org/

Friday, July 6, 2007

The factorial's tail recursive

Erlang:

-module(test).
-export([fac/1]).
fac(N) -> fac(N,1).

fac(0,A) -> A;
fac(N,A) -> fac(N-1,N*A).
--------------------------------
Haskell:

module Fac
where

fac(n)=facit(n,1)
facit(0,m) = m
facit(n,m)=facit(n-1,n*m)

Saturday, April 28, 2007

Concurrent Programming 相關報告

一. 我會接觸Erlang的緣由
1.RFID Middleware




2.jabber (xml::stream http://zh.wikipedia.org/wiki/Jabber)

3.ejabber (http://www.process-one.net/en/ )


二. 現在的商業環境(web server)所面臨的問題
1.連線的數量不斷的攀升

2.連線的時間很長
傳統上httpd 使用Prefork的方式來解決,短時間時密集連線的問題,在現在的環境愈到了嚴重的挑戰,比如: HTTP_Streaming、Server Push、COMET 這些需要長時間連線的架構,使得httpd 能夠服務的連線變少了,而fork process 最大的問題是,他所需要佔用記憶體的空間過於龐大,於是其他的伺服器架構崛起(lighthttpd ghttpd …)

The C10K problem( http://www.kegel.com/c10k.html )
It's time for web servers to handle ten thousand clients simultaneously, don't you think? After all, the web is a big place now.
And computers are big, too. You can buy a 1000MHz machine with 2 gigabytes of RAM and an 1000Mbit/sec Ethernet card for $1200 or so. Let's see - at 20000 clients, that's 50KHz, 100Kbytes, and 50Kbits/sec per client. It shouldn't take any more horsepower than that to take four kilobytes from the disk and send them to the network once a second for each of twenty thousand clients. (That works out to $0.08 per client, by the way. Those $100/client licensing fees some operating systems charge are starting to look a little heavy!) So hardware is no longer the bottleneck???


三. Concurrent Programming
1. fork
原始的程式
(程式+資料) --fork(複製一份)(程式+資料)

當程式fork 後,child 繼承原來的資料,此後彼此不相關,如果要傳遞資訊,需要使用pipe sharememory 或是 unix socket 來做資料交換

2. thread
事實上在Linux 系統下,執行緒只是一個light weight process:Linux 核心是以fork() system call 來產生一個新的行程(process),而執行緒是以clone() system call 產生的。fork()和clone()的差別只是在clone()可以指定和父行程共用的資源有哪些,當所有資源都和父行程共用時就相當於一個執行緒了。因為Thread 的使用會讓子父行程共用資源,因此非常容易引發dead lock / race condition …這類的問題

3. lightweight Threads ( http://www.defmacro.org/ramblings/concurrency.html)
Erlang process 是一個輕量級的Thread,因此他可以非常輕易的去開啟或是結束且快速在彼此做切換,因為掀開他的底層,他只是一個簡單的function罷了,process節省了大量的context switching浪費僅在一些function上做切換的動作(Erlang 的Thread 是 vm level thread)

這份文件簡單的提到了Erlang的概觀
http://mirror.linux.org.au/pub/linux.conf.au/2007/video/talks
/252.pdf


四. Erlang ( http://www.erlang.org/ )
1.以下是 about Erlang 對他自己的簡述

Erlang is a programming language which has many features more commonly associated with an operating system than with a programming language: concurrent processes, scheduling, memory management, distribution, networking, etc.
The initial open-source Erlang release contains the implementation of Erlang, as well as a large part of Ericsson's middleware for building distributed high-availability systems.
Erlang is characterized by the following features:
Concurrency - Erlang has extremely lightweight processes whose memory requirements can vary dynamically. Processes have no shared memory and communicate by asynchronous message passing. Erlang supports applications with very large numbers of concurrent processes. No requirements for concurrency are placed on the host operating system.
Distribution - Erlang is designed to be run in a distributed environment. An Erlang virtual machine is called an Erlang node. A distributed Erlang system is a network of Erlang nodes (typically one per processor). An Erlang node can create parallel processes running on other nodes, which perhaps use other operating systems. Processes residing on different nodes communicate in exactly the same was as processes residing on the same node.
Soft real-time - Erlang supports programming "soft" real-time systems, which require response times in the order of milliseconds. Long garbage collection delays in such systems are unacceptable, so Erlang uses incremental garbage collection techniques.
Hot code upgrade - Many systems cannot be stopped for software maintenance. Erlang allows program code to be changed in a running system. Old code can be phased out and replaced by new code. During the transition, both old code and new code can coexist. It is thus possible to install bug fixes and upgrades in a running system without disturbing its operation.
Incremental code loading - Users can control in detail how code is loaded. In embedded systems, all code is usually loaded at boot time. In development systems, code is loaded when it is needed, even when the system is running. If testing uncovers bugs, only the buggy code need be replaced.
External interfaces - Erlang processes communicate with the outside world using the same message passing mechanism as used between Erlang processes. This mechanism is used for communication with the host operating system and for interaction with programs written in other languages. If required for reasons of efficiency, a special version of this concept allows e.g. C programs to be directly linked into the Erlang runtime system.

2.Erlang 語言上的概觀
書籍: ( http://pragmaticprogrammer.com/titles/jaerlang/index.html )

[ Sequential Erlang ]

Exam1:

Consider the factorial function N! defined by:
N!=N*(N-1) when N>0
N!=1 when N=0

-module(math1).
-export([fac/1]).

fac(N) when N > 0 -> N * fac(N-1);
fac(0)-> 1.

Exam2:

-module(math2).
-export([sum1/1, sum2/1]).

sum1([H T]) -> H + sum1(T);
sum1([]) -> 0.

sum2(L) -> sum2(L, 0).
sum2([], N) -> N;
sum2([H T], N) -> sum2(T, H+N).

[ Concurrency Programming ]

Exam3:

-module(concurrency).

-export([start/0, say /2]).

say (What, 0) ->
done;
say (What, Times) ->
io:format("~p~n", [What]),
say_something(What, Times - 1).

start() ->
spawn(tut14, say, [hello, 3]),
spawn(tut14, say, [goodbye, 3]).

Exam4:

-module(area_server).
-export([loop/0]).

loop() ->
receive
{rectangle, Width, Ht} ->
io:format("Area of rectangle is ~p~n",[Width * Ht]),
loop();
{circle, R} ->
io:format("Area of circle is ~p~n", [3.14159 * R * R]),
loop();
Other ->
io:format("I don't know what the area of a ~p is ~n",[Other]),
loop()
end.

We can create a process which evaluates loop/0 in the shell:

Pid = spawn(area_server,loop,[]).
Pid ! {rectangle, 6, 10}.
Pid ! {circle, 23}.
Pid ! {triangle,2,4,5}.


4. Erlang –style process or event-based model for actors ( http://lambda-the-ultimate.org/node/1615 )
( http://lamp.epfl.ch/~phaller/doc/haller07coord.pdf )


Message passing
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.
Of course the Erlang implementation is "clever" and minimizes the number of times each message is tested against the patterns in each receive.
五. Erlang相關資源
Website:
Open Source Erlang
http://www.erlang.org
http://www.process-one.net/en/projects/

Mail List:
Erlang-questions -- Erlang/OTP discussions
http://www.erlang.org/mailman/listinfo/erlang-questions

BOOK:
Concurrent programming in Erlang
http://www.erlang.org/download/erlang-book-part1.pdf
Programming Erlang Software for a Concurrent World
http://pragmaticprogrammer.com/titles/jaerlang/index.html

Tuesday, April 10, 2007

遊戲開發人員眼中下一代的程式語言

這文章原是我的恩師在討論過程提到的一篇文章,文章裡提到一些目前c++ 遇到的問題,並且使用haskell去討論一些可能的解決方法

The Next Mainstream Programming Language: A Game Developer's Perspective
by Tim Sweeny (from Epic Games, Unreal)

http://www.st.cs.uni-sb.de/edu/seminare/2005/advanced-fp/docs/sweeny.pdf

這讓我想起另一篇介紹concurrency programming/erlang的文章
http://mirror.linux.org.au/pub/linux.conf.au/2007/video/talks/
252.pdf
後來我才意會過來;原來之前看的這篇文章有一小段是由上面的文章片段

另一個不錯的連結(介紹相關問題)
http://www.algorithm.com.au/talks/concurrency-erlang/

Blog Archive