Created
September 20, 2016 06:12
-
-
Save redink/919fec794887d9624d20f1022f4ac224 to your computer and use it in GitHub Desktop.
This file contains 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(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