Skip to content

Instantly share code, notes, and snippets.

@redink
Created September 20, 2016 06:12
Show Gist options
  • Save redink/919fec794887d9624d20f1022f4ac224 to your computer and use it in GitHub Desktop.
Save redink/919fec794887d9624d20f1022f4ac224 to your computer and use it in GitHub Desktop.
-module(tiny_pmap).
-export([pmap/2]).
-define(CONTASKNUM, 2).
pmap(Fun, List) ->
pmap(List, Fun, 1, [], []).
pmap([], _, _, [], ResList) ->
ResList;
pmap([], _, _, RefList, ResList) ->
ResList ++ lists:reverse([task:await(Ref) || Ref <- RefList]);
pmap([Head | Tail], Fun, N, RefList, ResList) ->
{NewResList, NewRefList, NewN} = pmap_flush(ResList, RefList, N),
pmap(Tail, Fun, NewN + 1,
[task:async(erlang, apply, [Fun, [Head]]) | NewRefList], NewResList).
pmap_flush(ResList, RefList, N) ->
case N rem (?CONTASKNUM + 1) of
0 ->
NewResList = ResList ++ lists:reverse([task:await(Ref) || Ref <- RefList]),
{NewResList, [], 1};
_ ->
{ResList, RefList, N}
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment