Erlang備忘:parallel map

[url]http://www.pkblogs.com/montsamu/2007/02/erlang-parallel-map-and-parallel.html[/url]

Joe Armstrong 提出了一個pmap實現

[code]pmap(F, L) ->
S = self(),
Pids = map(fun(I) ->
spawn(fun() -> do_f(S, F, I) end)
end, L),
gather(Pids).

gather([H|T]) ->
receive
{H, Ret} -> [Ret|gather(T)]
end;
gather([]) ->
[].

do_f(Parent, F, I) ->
Parent ! {self(), (catch F(I))}.[/code]

嗯,相當不錯,Master-Worker模式。

有人在回覆那裏提供了一個List Comprehensions方案

[code]parmap(F, L) ->
Parent = self(),
[receive {Pid, Result} -> Result end || Pid <- [spawn(fun() -> Parent ! {self(), F(X)} end) || X <- L]].[/code]

第一個列表
[spawn(fun() -> Parent ! {self(), F(X)} end) || X <- L]
生成了一系列worker進程,計算F(X)

第二個列表
[receive {Pid, Result} -> Result end || Pid <- ...]
收集計算結果,然後返回一個結果列表
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章