A Parallel Processing Template for Divide & Conquer Problems The Next CEO of Stack OverflowGeneral multithreaded file processingA Simple Thread Pool in ScalaQueue for distributing tasks between threadsDynamic Multi-threading lock with while loopMultithreaded brute force prime generatorRelaying stdin data from one thread to anotherConcurrent FIFO in C++11Dynamically extensible threadpool implementation in CSimple versatile thread poolMulti-threaded tree search

Why do we use the plural of movies in this phrase "We went to the movies last night."?

How are problems classified in Complexity Theory?

How do we know the LHC results are robust?

What is ( CFMCC ) on ILS approach chart?

Is micro rebar a better way to reinforce concrete than rebar?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Interfacing a button to MCU (and PC) with 50m long cable

A "random" question: usage of "random" as adjective in Spanish

At which OSI layer a user-generated data resides?

What benefits would be gained by using human laborers instead of drones in deep sea mining?

What does "Its cash flow is deeply negative" mean?

FBX seems to be empty when imported into Blender

Why does standard notation not preserve intervals (visually)

What connection does MS Office have to Netscape Navigator?

Was a professor correct to chastise me for writing "Prof. X" rather than "Professor X"?

Can I equip Skullclamp on a creature I am sacrificing?

Is there a difference between "Fahrstuhl" and "Aufzug"

MessageLevel in QGIS3

What's the best way to handle refactoring a big file?

What exact does MIB represent in SNMP? How is it different from OID?

What is the purpose of the Evocation wizard's Potent Cantrip feature?

SOQL: Aggregate, Grouping By and WHERE Clauses not working

Is it professional to write unrelated content in an almost-empty email?

Do I need to enable Dev Hub in my PROD Org?



A Parallel Processing Template for Divide & Conquer Problems



The Next CEO of Stack OverflowGeneral multithreaded file processingA Simple Thread Pool in ScalaQueue for distributing tasks between threadsDynamic Multi-threading lock with while loopMultithreaded brute force prime generatorRelaying stdin data from one thread to anotherConcurrent FIFO in C++11Dynamically extensible threadpool implementation in CSimple versatile thread poolMulti-threaded tree search










0












$begingroup$


I’ve written a program for solving a problem using standard single-threaded code. However, it looks like it could be recast as a multi-threaded problem using divide & conquer. Since this is a first attempt at multi-thread programming (and debugging), I thought it might be advisable to separate the problem itself from the parallel management. The following is a multi-threaded divide & conquer skeleton, which hopefully the actual problem could fit into. I would appreciate a code check and any relevant advice about how to better code multi-threaded applications like this.



The skeleton uses the Lparallel library with queues for communicating among the threads. There is a main thread which initializes the queues & threads, submits the problem, and then blocks waiting for a solution. The problem is submitted to a pool of threads, whose number can range up to one less than the number of hardware processors available. Each idle thread blocks until a (sub)problem becomes available on the problems queue, which it may then then capture. If the problem size is above a minimal problem-size-cutoff, the thread splits off a subproblem (randomly to simulate the uncertainty in how much future processing the subproblem will require). The subproblem is pushed onto the problems queue so another idle thread can deal with it subsequently, and the thread then continues processing with what’s remaining of the problem after the split. When a thread finishes working on its problem, it reports that it is now idle via the idles queue. When any thread (namely, the last thread running) observes that all threads are idle, it reports problem complete via the done queue.



To run the following code, simply switch to the :test package and execute (main) after loading. The printout shows when any thread receives a problem (its size—eg, 34), and if it is split, what the random split is—eg, (13 21). If it is not split because it is too small, the printout just shows the simulated processing of what’s remaining.



Secondary questions: 1) The function main uses up a whole thread just waiting for problem completion. Is there a way to use this thread too? 2) Can the number of queues or queue accesses be reduced? 3) Would a so-called sequence diagram be the best way to verify correctness? Ie, is this worth learning, or is there a better way. (Ps: The program seems to run OK, but I’m not even sure how to simulate the duration of a thread.) Thanks for any time you can spare.



#-:lparallel (ql:quickload :lparallel)

(defpackage :test (:use :cl :lparallel :lparallel.queue :lparallel.kernel-util))

(in-package :test)

(defparameter *num-threads* 2) ;available problem-solving threads (excludes main thread-0)

(defparameter *problem* 100) ;estimated size of the main problem

(defparameter *problem-size-cutoff* 5) ;don't split small (x2) problems


(defun thread (problems idles done)
"Definition for a problem-solving thread."
(loop do
(let ((problem (pop-queue problems))) ;blocks until a problem is available
(pop-queue idles) ;one (this) thread is no longer idle
(loop do
(print problem)
(when (and (> problem (* 2 *problem-size-cutoff*)) ;don't split if small problem
(>= (queue-count idles) 1)) ;ie, some threads are idle
(let ((n (+ (random (- problem (* 2 *problem-size-cutoff*)))
*problem-size-cutoff*))) ;split problem
(sleep .01) ;time to run splitting algorithm
(push-queue n problems) ;n is random size of subproblem split
(setf problem (- problem n)) ;remaining problem size after split
(print (list n problem))))
(decf problem) (sleep .1) ;work more on current problem
(when (= problem 0) ;is this thread's task complete?
(push-queue t idles) ;this thread now idle
(if (= (queue-count idles) *num-threads*) ;all threads idle
(progn (push-queue t done) ;signal all done to main
(return-from thread))
(return))))))) ;return from inner loop to get new problem


(defun main ()
"The main consumer of parallel thread processing."
(with-temp-kernel (1)
(let ((c (make-channel))
(problems (make-queue)) ;holds current problems to be solved
(idles (make-queue)) ;holds a t for each current idle thread
(done (make-queue))) ;signals t when all processing is done
(loop for i from 1 to *num-threads* ;get all threads up & running
do (submit-task c #'thread problems idles done)
(push-queue t idles)) ;each t in idles means a thread is currently idle
(push-queue *problem* problems) ;send the main problem to the thread pool
(pop-queue done)))) ;block until thread pool reports done








share









$endgroup$
















    0












    $begingroup$


    I’ve written a program for solving a problem using standard single-threaded code. However, it looks like it could be recast as a multi-threaded problem using divide & conquer. Since this is a first attempt at multi-thread programming (and debugging), I thought it might be advisable to separate the problem itself from the parallel management. The following is a multi-threaded divide & conquer skeleton, which hopefully the actual problem could fit into. I would appreciate a code check and any relevant advice about how to better code multi-threaded applications like this.



    The skeleton uses the Lparallel library with queues for communicating among the threads. There is a main thread which initializes the queues & threads, submits the problem, and then blocks waiting for a solution. The problem is submitted to a pool of threads, whose number can range up to one less than the number of hardware processors available. Each idle thread blocks until a (sub)problem becomes available on the problems queue, which it may then then capture. If the problem size is above a minimal problem-size-cutoff, the thread splits off a subproblem (randomly to simulate the uncertainty in how much future processing the subproblem will require). The subproblem is pushed onto the problems queue so another idle thread can deal with it subsequently, and the thread then continues processing with what’s remaining of the problem after the split. When a thread finishes working on its problem, it reports that it is now idle via the idles queue. When any thread (namely, the last thread running) observes that all threads are idle, it reports problem complete via the done queue.



    To run the following code, simply switch to the :test package and execute (main) after loading. The printout shows when any thread receives a problem (its size—eg, 34), and if it is split, what the random split is—eg, (13 21). If it is not split because it is too small, the printout just shows the simulated processing of what’s remaining.



    Secondary questions: 1) The function main uses up a whole thread just waiting for problem completion. Is there a way to use this thread too? 2) Can the number of queues or queue accesses be reduced? 3) Would a so-called sequence diagram be the best way to verify correctness? Ie, is this worth learning, or is there a better way. (Ps: The program seems to run OK, but I’m not even sure how to simulate the duration of a thread.) Thanks for any time you can spare.



    #-:lparallel (ql:quickload :lparallel)

    (defpackage :test (:use :cl :lparallel :lparallel.queue :lparallel.kernel-util))

    (in-package :test)

    (defparameter *num-threads* 2) ;available problem-solving threads (excludes main thread-0)

    (defparameter *problem* 100) ;estimated size of the main problem

    (defparameter *problem-size-cutoff* 5) ;don't split small (x2) problems


    (defun thread (problems idles done)
    "Definition for a problem-solving thread."
    (loop do
    (let ((problem (pop-queue problems))) ;blocks until a problem is available
    (pop-queue idles) ;one (this) thread is no longer idle
    (loop do
    (print problem)
    (when (and (> problem (* 2 *problem-size-cutoff*)) ;don't split if small problem
    (>= (queue-count idles) 1)) ;ie, some threads are idle
    (let ((n (+ (random (- problem (* 2 *problem-size-cutoff*)))
    *problem-size-cutoff*))) ;split problem
    (sleep .01) ;time to run splitting algorithm
    (push-queue n problems) ;n is random size of subproblem split
    (setf problem (- problem n)) ;remaining problem size after split
    (print (list n problem))))
    (decf problem) (sleep .1) ;work more on current problem
    (when (= problem 0) ;is this thread's task complete?
    (push-queue t idles) ;this thread now idle
    (if (= (queue-count idles) *num-threads*) ;all threads idle
    (progn (push-queue t done) ;signal all done to main
    (return-from thread))
    (return))))))) ;return from inner loop to get new problem


    (defun main ()
    "The main consumer of parallel thread processing."
    (with-temp-kernel (1)
    (let ((c (make-channel))
    (problems (make-queue)) ;holds current problems to be solved
    (idles (make-queue)) ;holds a t for each current idle thread
    (done (make-queue))) ;signals t when all processing is done
    (loop for i from 1 to *num-threads* ;get all threads up & running
    do (submit-task c #'thread problems idles done)
    (push-queue t idles)) ;each t in idles means a thread is currently idle
    (push-queue *problem* problems) ;send the main problem to the thread pool
    (pop-queue done)))) ;block until thread pool reports done








    share









    $endgroup$














      0












      0








      0





      $begingroup$


      I’ve written a program for solving a problem using standard single-threaded code. However, it looks like it could be recast as a multi-threaded problem using divide & conquer. Since this is a first attempt at multi-thread programming (and debugging), I thought it might be advisable to separate the problem itself from the parallel management. The following is a multi-threaded divide & conquer skeleton, which hopefully the actual problem could fit into. I would appreciate a code check and any relevant advice about how to better code multi-threaded applications like this.



      The skeleton uses the Lparallel library with queues for communicating among the threads. There is a main thread which initializes the queues & threads, submits the problem, and then blocks waiting for a solution. The problem is submitted to a pool of threads, whose number can range up to one less than the number of hardware processors available. Each idle thread blocks until a (sub)problem becomes available on the problems queue, which it may then then capture. If the problem size is above a minimal problem-size-cutoff, the thread splits off a subproblem (randomly to simulate the uncertainty in how much future processing the subproblem will require). The subproblem is pushed onto the problems queue so another idle thread can deal with it subsequently, and the thread then continues processing with what’s remaining of the problem after the split. When a thread finishes working on its problem, it reports that it is now idle via the idles queue. When any thread (namely, the last thread running) observes that all threads are idle, it reports problem complete via the done queue.



      To run the following code, simply switch to the :test package and execute (main) after loading. The printout shows when any thread receives a problem (its size—eg, 34), and if it is split, what the random split is—eg, (13 21). If it is not split because it is too small, the printout just shows the simulated processing of what’s remaining.



      Secondary questions: 1) The function main uses up a whole thread just waiting for problem completion. Is there a way to use this thread too? 2) Can the number of queues or queue accesses be reduced? 3) Would a so-called sequence diagram be the best way to verify correctness? Ie, is this worth learning, or is there a better way. (Ps: The program seems to run OK, but I’m not even sure how to simulate the duration of a thread.) Thanks for any time you can spare.



      #-:lparallel (ql:quickload :lparallel)

      (defpackage :test (:use :cl :lparallel :lparallel.queue :lparallel.kernel-util))

      (in-package :test)

      (defparameter *num-threads* 2) ;available problem-solving threads (excludes main thread-0)

      (defparameter *problem* 100) ;estimated size of the main problem

      (defparameter *problem-size-cutoff* 5) ;don't split small (x2) problems


      (defun thread (problems idles done)
      "Definition for a problem-solving thread."
      (loop do
      (let ((problem (pop-queue problems))) ;blocks until a problem is available
      (pop-queue idles) ;one (this) thread is no longer idle
      (loop do
      (print problem)
      (when (and (> problem (* 2 *problem-size-cutoff*)) ;don't split if small problem
      (>= (queue-count idles) 1)) ;ie, some threads are idle
      (let ((n (+ (random (- problem (* 2 *problem-size-cutoff*)))
      *problem-size-cutoff*))) ;split problem
      (sleep .01) ;time to run splitting algorithm
      (push-queue n problems) ;n is random size of subproblem split
      (setf problem (- problem n)) ;remaining problem size after split
      (print (list n problem))))
      (decf problem) (sleep .1) ;work more on current problem
      (when (= problem 0) ;is this thread's task complete?
      (push-queue t idles) ;this thread now idle
      (if (= (queue-count idles) *num-threads*) ;all threads idle
      (progn (push-queue t done) ;signal all done to main
      (return-from thread))
      (return))))))) ;return from inner loop to get new problem


      (defun main ()
      "The main consumer of parallel thread processing."
      (with-temp-kernel (1)
      (let ((c (make-channel))
      (problems (make-queue)) ;holds current problems to be solved
      (idles (make-queue)) ;holds a t for each current idle thread
      (done (make-queue))) ;signals t when all processing is done
      (loop for i from 1 to *num-threads* ;get all threads up & running
      do (submit-task c #'thread problems idles done)
      (push-queue t idles)) ;each t in idles means a thread is currently idle
      (push-queue *problem* problems) ;send the main problem to the thread pool
      (pop-queue done)))) ;block until thread pool reports done








      share









      $endgroup$




      I’ve written a program for solving a problem using standard single-threaded code. However, it looks like it could be recast as a multi-threaded problem using divide & conquer. Since this is a first attempt at multi-thread programming (and debugging), I thought it might be advisable to separate the problem itself from the parallel management. The following is a multi-threaded divide & conquer skeleton, which hopefully the actual problem could fit into. I would appreciate a code check and any relevant advice about how to better code multi-threaded applications like this.



      The skeleton uses the Lparallel library with queues for communicating among the threads. There is a main thread which initializes the queues & threads, submits the problem, and then blocks waiting for a solution. The problem is submitted to a pool of threads, whose number can range up to one less than the number of hardware processors available. Each idle thread blocks until a (sub)problem becomes available on the problems queue, which it may then then capture. If the problem size is above a minimal problem-size-cutoff, the thread splits off a subproblem (randomly to simulate the uncertainty in how much future processing the subproblem will require). The subproblem is pushed onto the problems queue so another idle thread can deal with it subsequently, and the thread then continues processing with what’s remaining of the problem after the split. When a thread finishes working on its problem, it reports that it is now idle via the idles queue. When any thread (namely, the last thread running) observes that all threads are idle, it reports problem complete via the done queue.



      To run the following code, simply switch to the :test package and execute (main) after loading. The printout shows when any thread receives a problem (its size—eg, 34), and if it is split, what the random split is—eg, (13 21). If it is not split because it is too small, the printout just shows the simulated processing of what’s remaining.



      Secondary questions: 1) The function main uses up a whole thread just waiting for problem completion. Is there a way to use this thread too? 2) Can the number of queues or queue accesses be reduced? 3) Would a so-called sequence diagram be the best way to verify correctness? Ie, is this worth learning, or is there a better way. (Ps: The program seems to run OK, but I’m not even sure how to simulate the duration of a thread.) Thanks for any time you can spare.



      #-:lparallel (ql:quickload :lparallel)

      (defpackage :test (:use :cl :lparallel :lparallel.queue :lparallel.kernel-util))

      (in-package :test)

      (defparameter *num-threads* 2) ;available problem-solving threads (excludes main thread-0)

      (defparameter *problem* 100) ;estimated size of the main problem

      (defparameter *problem-size-cutoff* 5) ;don't split small (x2) problems


      (defun thread (problems idles done)
      "Definition for a problem-solving thread."
      (loop do
      (let ((problem (pop-queue problems))) ;blocks until a problem is available
      (pop-queue idles) ;one (this) thread is no longer idle
      (loop do
      (print problem)
      (when (and (> problem (* 2 *problem-size-cutoff*)) ;don't split if small problem
      (>= (queue-count idles) 1)) ;ie, some threads are idle
      (let ((n (+ (random (- problem (* 2 *problem-size-cutoff*)))
      *problem-size-cutoff*))) ;split problem
      (sleep .01) ;time to run splitting algorithm
      (push-queue n problems) ;n is random size of subproblem split
      (setf problem (- problem n)) ;remaining problem size after split
      (print (list n problem))))
      (decf problem) (sleep .1) ;work more on current problem
      (when (= problem 0) ;is this thread's task complete?
      (push-queue t idles) ;this thread now idle
      (if (= (queue-count idles) *num-threads*) ;all threads idle
      (progn (push-queue t done) ;signal all done to main
      (return-from thread))
      (return))))))) ;return from inner loop to get new problem


      (defun main ()
      "The main consumer of parallel thread processing."
      (with-temp-kernel (1)
      (let ((c (make-channel))
      (problems (make-queue)) ;holds current problems to be solved
      (idles (make-queue)) ;holds a t for each current idle thread
      (done (make-queue))) ;signals t when all processing is done
      (loop for i from 1 to *num-threads* ;get all threads up & running
      do (submit-task c #'thread problems idles done)
      (push-queue t idles)) ;each t in idles means a thread is currently idle
      (push-queue *problem* problems) ;send the main problem to the thread pool
      (pop-queue done)))) ;block until thread pool reports done






      multithreading common-lisp multiprocessing divide-and-conquer





      share












      share










      share



      share










      asked 2 mins ago









      davypoughdavypough

      1835




      1835




















          0






          active

          oldest

          votes












          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',
          autoActivateHeartbeat: false,
          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%2f216500%2fa-parallel-processing-template-for-divide-conquer-problems%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          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.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216500%2fa-parallel-processing-template-for-divide-conquer-problems%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

          瀋陽號驅逐艦 目录 接收與服役 配置反潛直升機 武進三型性能升級 歷史 除役 參考資料 外部連結 导航菜单Taiwan Air Power海疆老兵-陽字號驅逐艦沿革World Navies Today: Taiwan (Republic of China)DD-839 USS POWER编

          波兰旗帜列表 目录 国旗 军旗 其他制服部门旗帜 特别国家机构船只 参考文献 外部链接 导航菜单Polskie flagi, chorągwie, bandery... [波兰旗帜、条幅、船旗等]原始内容Ustawa z dnia 31 stycznia 1980 r. o godle, barwach i hymnie Rzeczypospolitej Polskiej oraz o pieczęciach państwowychZarządzenie Ministra Obrony Narodowej z dnia 14 grudnia 2005 r. zmieniające zarządzenie w sprawie szczegółowych zasad używania znaków Sił Zbrojnych Rzeczypospolitej Polskiej oraz ustalenia innych znaków używanych w Siłach Zbrojnych Rzeczypospolitej PolskiejZarządzenie Ministra Obrony Narodowej z dnia 29 stycznia 1996 r. w sprawie szczegółowych zasad używania znaków Sił Zbrojnych Rzeczypospolitej Polskiej oraz ustalenia innych znaków używanych w Siłach Zbrojnych Rzeczypospolitej PolskiejUstawa z dnia 19 lutego 1993 r. o znakach Sił Zbrojnych Rzeczypospolitej PolskiejHistoria Marynarki Wojennej RP [波兰海军史]Rozporządzenie Ministra Spraw Wewnętrznych i Administracji z dnia 12 kwietnia 2002 r. w sprawie wzoru flagi oraz oznakowania jednostek pływających i statków powietrznych Straży GranicznejRozporządzenie Ministra Spraw Wewnętrznych i Administracji z dnia 18 kwietnia 2005 r. w sprawie wzoru flagi oraz oznakowania jednostek pływających i statków powietrznych PolicjiRozporządzenie Ministra Infrastruktury z dnia 21 października 2005 r. w sprawie wzorów flag dla statków morskich na oznaczenie pełnionej specjalnej służby państwowej oraz okoliczności i warunków ich podnoszenia波兰旗帜波兰编

          Indenting and Dedenting ASP code with Python