Erlang: pmap with max number of processes











up vote
1
down vote

favorite












I'm working through Joe Armstrong's Programming Erlang 2nd E. The book has exercises at the end of each chapter. Chapter 26, Question 5 is:




Write a function called pmap(F, L, Max) that computes the list [F(I) || I <- L] in parallel but is subject to the restriction that no more than Max parallel processes run simultaneously.




My solution is:



-module(pmap_cap).
-export([pmap/3]).

pmap(F, L, Max) ->
S = self(),
Ref = make_ref(),
Pids = lists:map(fun(SubL) ->
spawn(fun() -> do_f(S, Ref, F, SubL) end)
end,
partition(L, min(length(L), Max))),
gather(Pids, Ref).

partition(L, N) ->
M = length(L),
if
M =< N -> lists:map(fun(X) -> [X] end, L);
true -> partition(L, M div N, M rem N)
end.

partition(, _Q, _R) -> ;
partition(L, Q, R) ->
Extra = if R > 0 -> 1; true -> 0 end,
[lists:sublist(L, Q + Extra)|
partition(lists:sublist(L, Q + Extra + 1, length(L)), Q, R-1)].

do_f(Parent, Ref, F, SubL) ->
Parent ! {self(), Ref, lists:map(fun(X) -> catch F(X) end, SubL)}.

gather([Pid|T], Ref) ->
receive
{Pid, Ref, Ret} ->
lists:append(Ret, gather(T, Ref))
end;
gather(, _) -> .


What could be improved? Are there performance issues? Can the code be written more idiomatically?










share|improve this question














bumped to the homepage by Community 38 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.



















    up vote
    1
    down vote

    favorite












    I'm working through Joe Armstrong's Programming Erlang 2nd E. The book has exercises at the end of each chapter. Chapter 26, Question 5 is:




    Write a function called pmap(F, L, Max) that computes the list [F(I) || I <- L] in parallel but is subject to the restriction that no more than Max parallel processes run simultaneously.




    My solution is:



    -module(pmap_cap).
    -export([pmap/3]).

    pmap(F, L, Max) ->
    S = self(),
    Ref = make_ref(),
    Pids = lists:map(fun(SubL) ->
    spawn(fun() -> do_f(S, Ref, F, SubL) end)
    end,
    partition(L, min(length(L), Max))),
    gather(Pids, Ref).

    partition(L, N) ->
    M = length(L),
    if
    M =< N -> lists:map(fun(X) -> [X] end, L);
    true -> partition(L, M div N, M rem N)
    end.

    partition(, _Q, _R) -> ;
    partition(L, Q, R) ->
    Extra = if R > 0 -> 1; true -> 0 end,
    [lists:sublist(L, Q + Extra)|
    partition(lists:sublist(L, Q + Extra + 1, length(L)), Q, R-1)].

    do_f(Parent, Ref, F, SubL) ->
    Parent ! {self(), Ref, lists:map(fun(X) -> catch F(X) end, SubL)}.

    gather([Pid|T], Ref) ->
    receive
    {Pid, Ref, Ret} ->
    lists:append(Ret, gather(T, Ref))
    end;
    gather(, _) -> .


    What could be improved? Are there performance issues? Can the code be written more idiomatically?










    share|improve this question














    bumped to the homepage by Community 38 mins ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I'm working through Joe Armstrong's Programming Erlang 2nd E. The book has exercises at the end of each chapter. Chapter 26, Question 5 is:




      Write a function called pmap(F, L, Max) that computes the list [F(I) || I <- L] in parallel but is subject to the restriction that no more than Max parallel processes run simultaneously.




      My solution is:



      -module(pmap_cap).
      -export([pmap/3]).

      pmap(F, L, Max) ->
      S = self(),
      Ref = make_ref(),
      Pids = lists:map(fun(SubL) ->
      spawn(fun() -> do_f(S, Ref, F, SubL) end)
      end,
      partition(L, min(length(L), Max))),
      gather(Pids, Ref).

      partition(L, N) ->
      M = length(L),
      if
      M =< N -> lists:map(fun(X) -> [X] end, L);
      true -> partition(L, M div N, M rem N)
      end.

      partition(, _Q, _R) -> ;
      partition(L, Q, R) ->
      Extra = if R > 0 -> 1; true -> 0 end,
      [lists:sublist(L, Q + Extra)|
      partition(lists:sublist(L, Q + Extra + 1, length(L)), Q, R-1)].

      do_f(Parent, Ref, F, SubL) ->
      Parent ! {self(), Ref, lists:map(fun(X) -> catch F(X) end, SubL)}.

      gather([Pid|T], Ref) ->
      receive
      {Pid, Ref, Ret} ->
      lists:append(Ret, gather(T, Ref))
      end;
      gather(, _) -> .


      What could be improved? Are there performance issues? Can the code be written more idiomatically?










      share|improve this question













      I'm working through Joe Armstrong's Programming Erlang 2nd E. The book has exercises at the end of each chapter. Chapter 26, Question 5 is:




      Write a function called pmap(F, L, Max) that computes the list [F(I) || I <- L] in parallel but is subject to the restriction that no more than Max parallel processes run simultaneously.




      My solution is:



      -module(pmap_cap).
      -export([pmap/3]).

      pmap(F, L, Max) ->
      S = self(),
      Ref = make_ref(),
      Pids = lists:map(fun(SubL) ->
      spawn(fun() -> do_f(S, Ref, F, SubL) end)
      end,
      partition(L, min(length(L), Max))),
      gather(Pids, Ref).

      partition(L, N) ->
      M = length(L),
      if
      M =< N -> lists:map(fun(X) -> [X] end, L);
      true -> partition(L, M div N, M rem N)
      end.

      partition(, _Q, _R) -> ;
      partition(L, Q, R) ->
      Extra = if R > 0 -> 1; true -> 0 end,
      [lists:sublist(L, Q + Extra)|
      partition(lists:sublist(L, Q + Extra + 1, length(L)), Q, R-1)].

      do_f(Parent, Ref, F, SubL) ->
      Parent ! {self(), Ref, lists:map(fun(X) -> catch F(X) end, SubL)}.

      gather([Pid|T], Ref) ->
      receive
      {Pid, Ref, Ret} ->
      lists:append(Ret, gather(T, Ref))
      end;
      gather(, _) -> .


      What could be improved? Are there performance issues? Can the code be written more idiomatically?







      erlang actor






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Feb 3 at 8:58









      Tianxiang Xiong

      1062




      1062





      bumped to the homepage by Community 38 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 38 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          General





          1. Use standard library as many as possible, usually it given better result therefore function partition can be easily rewritting with wrapper on lists:split/2 and it will be consider as perfomance improvement



            split(List,Max)->
            L = length(List),
            split_by(List,L rem Max + L div Max,).

            split_by(,_N,R)->lists:reverse(R);
            split_by(List,N,R)->
            {Part,NewList} = lists:split(N,List),
            split_by(NewList,N,[Part|R]).



          Idiomaticness




          1. Add to head of list and reverse instead append. For explanation - SO question.



          2. Tail recursion better for readability and may be faster, so function gather become:



            gather([Pid|T], Ref,R) ->
            receive
            {Pid, Ref, Ret} -> gather(T, Ref,[Ret|R])
            end;
            gather(, _,R) -> lists:flatten(lists:reverse(R)).



          3. List comprehensions instead lists:map/2:



            Min = min(length(L), Max),
            Pids = [spawn(
            fun() -> do_f(S, Ref, F, SubL) end) || SubL <- split(L, Min)],
            ...







          share|improve this answer





















            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186662%2ferlang-pmap-with-max-number-of-processes%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            General





            1. Use standard library as many as possible, usually it given better result therefore function partition can be easily rewritting with wrapper on lists:split/2 and it will be consider as perfomance improvement



              split(List,Max)->
              L = length(List),
              split_by(List,L rem Max + L div Max,).

              split_by(,_N,R)->lists:reverse(R);
              split_by(List,N,R)->
              {Part,NewList} = lists:split(N,List),
              split_by(NewList,N,[Part|R]).



            Idiomaticness




            1. Add to head of list and reverse instead append. For explanation - SO question.



            2. Tail recursion better for readability and may be faster, so function gather become:



              gather([Pid|T], Ref,R) ->
              receive
              {Pid, Ref, Ret} -> gather(T, Ref,[Ret|R])
              end;
              gather(, _,R) -> lists:flatten(lists:reverse(R)).



            3. List comprehensions instead lists:map/2:



              Min = min(length(L), Max),
              Pids = [spawn(
              fun() -> do_f(S, Ref, F, SubL) end) || SubL <- split(L, Min)],
              ...







            share|improve this answer

























              up vote
              0
              down vote













              General





              1. Use standard library as many as possible, usually it given better result therefore function partition can be easily rewritting with wrapper on lists:split/2 and it will be consider as perfomance improvement



                split(List,Max)->
                L = length(List),
                split_by(List,L rem Max + L div Max,).

                split_by(,_N,R)->lists:reverse(R);
                split_by(List,N,R)->
                {Part,NewList} = lists:split(N,List),
                split_by(NewList,N,[Part|R]).



              Idiomaticness




              1. Add to head of list and reverse instead append. For explanation - SO question.



              2. Tail recursion better for readability and may be faster, so function gather become:



                gather([Pid|T], Ref,R) ->
                receive
                {Pid, Ref, Ret} -> gather(T, Ref,[Ret|R])
                end;
                gather(, _,R) -> lists:flatten(lists:reverse(R)).



              3. List comprehensions instead lists:map/2:



                Min = min(length(L), Max),
                Pids = [spawn(
                fun() -> do_f(S, Ref, F, SubL) end) || SubL <- split(L, Min)],
                ...







              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                General





                1. Use standard library as many as possible, usually it given better result therefore function partition can be easily rewritting with wrapper on lists:split/2 and it will be consider as perfomance improvement



                  split(List,Max)->
                  L = length(List),
                  split_by(List,L rem Max + L div Max,).

                  split_by(,_N,R)->lists:reverse(R);
                  split_by(List,N,R)->
                  {Part,NewList} = lists:split(N,List),
                  split_by(NewList,N,[Part|R]).



                Idiomaticness




                1. Add to head of list and reverse instead append. For explanation - SO question.



                2. Tail recursion better for readability and may be faster, so function gather become:



                  gather([Pid|T], Ref,R) ->
                  receive
                  {Pid, Ref, Ret} -> gather(T, Ref,[Ret|R])
                  end;
                  gather(, _,R) -> lists:flatten(lists:reverse(R)).



                3. List comprehensions instead lists:map/2:



                  Min = min(length(L), Max),
                  Pids = [spawn(
                  fun() -> do_f(S, Ref, F, SubL) end) || SubL <- split(L, Min)],
                  ...







                share|improve this answer












                General





                1. Use standard library as many as possible, usually it given better result therefore function partition can be easily rewritting with wrapper on lists:split/2 and it will be consider as perfomance improvement



                  split(List,Max)->
                  L = length(List),
                  split_by(List,L rem Max + L div Max,).

                  split_by(,_N,R)->lists:reverse(R);
                  split_by(List,N,R)->
                  {Part,NewList} = lists:split(N,List),
                  split_by(NewList,N,[Part|R]).



                Idiomaticness




                1. Add to head of list and reverse instead append. For explanation - SO question.



                2. Tail recursion better for readability and may be faster, so function gather become:



                  gather([Pid|T], Ref,R) ->
                  receive
                  {Pid, Ref, Ret} -> gather(T, Ref,[Ret|R])
                  end;
                  gather(, _,R) -> lists:flatten(lists:reverse(R)).



                3. List comprehensions instead lists:map/2:



                  Min = min(length(L), Max),
                  Pids = [spawn(
                  fun() -> do_f(S, Ref, F, SubL) end) || SubL <- split(L, Min)],
                  ...








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 4 at 21:57







                user110702





































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186662%2ferlang-pmap-with-max-number-of-processes%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    Refactoring coordinates for Minecraft Pi buildings written in Python