Last active
May 10, 2018 08:19
-
-
Save mguenther/9283f8ccaadd18ba7a74 to your computer and use it in GitHub Desktop.
fork/join with parallel quicksort as example (Erlang)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(fj). | |
-export([parallel/2]). | |
%%%----------------------------------------------------------------------------- | |
%%% @doc Executes the given function on every task in tasks in parallel. | |
%%% @spec parallel(Function, Tasks) -> Results | |
%%% where Results is a list matching the arity of input list Tasks | |
%%% but contains the result of invoking Function on those tasks | |
%%% @end | |
%%%----------------------------------------------------------------------------- | |
parallel(Function, Tasks) -> | |
Pids = fork(Function, Tasks), | |
join(Pids). | |
%%------------------------------------------------------------------------------ | |
%% @doc Forks all tasks in given list Tasks to new Erlang processes. Those | |
%% processes invoke Function on forked tasks. | |
%% @spec fork(Function, Tasks) -> Pids | |
%% where Pids is a list of process IDs | |
%% @end | |
%%------------------------------------------------------------------------------ | |
fork(Function, Tasks) -> | |
Parent = self(), | |
Pids = lists:map(fun(Task) -> | |
spawn(fun() -> | |
invoke(Parent, Function, Task) | |
end) | |
end, Tasks), | |
Pids. | |
join([P|Ps]) -> | |
receive | |
{P, Result} -> [Result|join(Ps)] | |
end; | |
join([]) -> | |
[]. | |
invoke(Receiver, Function, Instance) -> | |
Receiver ! {self(), (catch Function(Instance))}. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(pqsort). | |
-export([pqsort/1]). | |
pqsort([]) -> []; | |
pqsort([Pivot]) -> [Pivot]; | |
pqsort([Pivot|Rest]) -> | |
io:format("+", []), | |
L = [X || X <- Rest, X < Pivot], | |
R = [Y || Y <- Rest, Y >= Pivot], | |
[SL, SR] = fj:parallel(fun pqsort/1, [L,R]), | |
io:format("-", []), | |
SL ++ [Pivot] ++ SR. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment