Skip to content

Instantly share code, notes, and snippets.

@limitedmage
Created October 5, 2010 05:09
Show Gist options
  • Save limitedmage/611028 to your computer and use it in GitHub Desktop.
Save limitedmage/611028 to your computer and use it in GitHub Desktop.
-module(mc).
-compile(export_all).
pmap(Fun, Lst) ->
% get current Pid
Self = self(),
% get a unique idendifier
Ref = erlang:make_ref(),
% create a process for every element in the list
% and run do_fun on them
Pids = lists:map(fun (X) ->
spawn(fun() -> do_fun(Self, Ref, Fun, X) end)
end, Lst),
% receive data and construct function
gather(Pids, Ref).
do_fun(Sender, Ref, Fun, X) ->
% run Fun, and catch error if Fun aborts
Sender ! {self(), Ref, (catch Fun(X))}.
gather([], _) -> [];
gather([Pid | T], Ref) ->
% gather the results in order and recursively
receive
{Pid, Ref, Result} -> [Result | gather(T, Ref)]
end.
fib(0) -> 0;
fib(1) -> 1;
fib(N) when N > 0 -> fib(N - 1) + fib(N - 2).
test() ->
Lst = lists:duplicate(100, 27),
{Time1, Result1} = timer:tc(lists, map, [fun fib/1, Lst]),
{Time2, Result2} = timer:tc(?MODULE, pmap, [fun fib/1, Lst]),
io:format("Results are equal: ~w, speedup = ~w~n", [Result1 == Result2, Time1 / Time2]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment