Erlang备忘:parallel map

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

Joe Armstrong 提出了一个pmap实现

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))}.


嗯,相当不错,Master-Worker模式。

有人在回复那里提供了一个List Comprehensions方案

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


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

第二个列表
[receive {Pid, Result} -> Result end || Pid <- ...]
收集计算结果,然后返回一个结果列表

你可能感兴趣的:(html,erlang,F#)