Multithreading: Multithreaded design Mode (iii): Master-worker mode

Source: Internet
Author: User

Master-worker mode is one of the common parallel patterns, its core idea is that the system has two processes work together: master process, responsible for receiving and assigning tasks, worker process, responsible for processing subtasks. When the worker process finishes processing the child tasks, the results are returned to the master process, summarized by the master process, and finally the results are obtained.

First, what is the Master-worker mode:

Structure diagram for this pattern:

Structure diagram:

Worker: Used to actually handle a task;

Master: Assignment of tasks and synthesis of the final result;

Main: Start the program and the scheduler opens master.

Second, the code implementation:

The following is a simple implementation of the Master-worker framework.

(1) Master section:

[Java]View PlainCopy
  1. Package masterworker;
  2. Import Java.util.HashMap;
  3. Import Java.util.Map;
  4. Import Java.util.Queue;
  5. Import Java.util.concurrent.ConcurrentHashMap;
  6. Import Java.util.concurrent.ConcurrentLinkedQueue;
  7. Public class Master {
  8. //Task Queue
  9. protected queue<object> workqueue= new concurrentlinkedqueue<object> ();
  10. //worker Process Queue
  11. protected map<string,thread> threadmap= new hashmap<string,thread> ();
  12. //Sub-task processing result set
  13. protected map<string,object> resultmap= new concurrenthashmap<string, object> ();
  14. //Whether all sub-tasks are over
  15. Public Boolean iscomplete () {
  16. for (map.entry<string, thread> entry:threadMap.entrySet ()) {
  17. if (Entry.getvalue (). GetState ()!=thread.state.terminated) {
  18. return false;
  19. }
  20. }
  21. return true;
  22. }
  23. //master constructs, requires a worker process logic, and the number of worker processes required
  24. Public Master (worker worker,int countworker) {
  25. Worker.setworkqueue (WorkQueue);
  26. Worker.setresultmap (RESULTMAP);
  27. For (int i=0;i<countworker;i++) {
  28. Threadmap.put (Integer.tostring (i), new Thread (worker, integer.tostring (i)));
  29. }
  30. }
  31. //Submit a task
  32. public void Submit (Object job) {
  33. Workqueue.add (Job);
  34. }
  35. //Return child task result set
  36. Public map<string,object> Getresultmap () {
  37. return resultmap;
  38. }
  39. //Start running all worker processes for processing
  40. public Void execute () {
  41. for (map.entry<string, thread> entry:threadMap.entrySet ()) {
  42. Entry.getvalue (). Start ();
  43. }
  44. }
  45. }

(2) Worker process implementation:

[Java]View PlainCopy
  1. Package masterworker;
  2. Import Java.util.Map;
  3. Import Java.util.Queue;
  4. Public class Worker implements runnable{
  5. //Task queue for sub-task acquisition
  6. protected queue<object> workQueue;
  7. //Sub-task processing result set
  8. protected map<string,object> resultmap;
  9. public void Setworkqueue (queue<object> workQueue) {
  10. this.workqueue= WorkQueue;
  11. }
  12. public void Setresultmap (map<string,object> resultmap) {
  13. This.resultmap=resultmap;
  14. }
  15. //Sub-task processing logic, implementing specific logic in subclasses
  16. Public object handle (object input) {
  17. return input;
  18. }
  19. @Override
  20. public Void Run () {
  21. While (true) {
  22. //Get child tasks
  23. Object input= Workqueue.poll ();
  24. if (input==null) {
  25. Break ;
  26. }
  27. //Handling subtasks
  28. Object re = handle (input);
  29. Resultmap.put (Integer.tostring (Input.hashcode ()), re);
  30. }
  31. }
  32. }

(3) Using this small framework to calculate 1--100 's cubic and, Plusworker implementations:

[Java]View PlainCopy
  1. Package masterworker;
  2. Public class Plusworker extends Worker {
  3. @Override
  4. Public object handle (object input) {
  5. Integer i = (integer) input;
  6. return i*i*i;
  7. }
  8. }

(4) The main function for the calculation:

[Java]View PlainCopy
  1. Package masterworker;
  2. Import Java.util.Map;
  3. Import Java.util.Set;
  4. Public class Main {
  5. /** 
  6. * @param args
  7. */
  8. public static void Main (string[] args) {
  9. //fixed use of 5 worker and specified worker
  10. Master m = new Master (new Plusworker (), 5);
  11. //Submit 100 sub-tasks
  12. For (int i=0;i<100;i++) {
  13. M.submit (i);
  14. }
  15. //Start calculation
  16. M.execute ();
  17. int re= 0;
  18. //Save Final settlement results
  19. Map<string,object> Resultmap =m.getresultmap ();
  20. //Do not wait for all workers to complete to begin calculating the final result
  21. While (Resultmap.size () >0 | |!m.iscomplete ()) {
  22. set<string> keys = Resultmap.keyset ();
  23. String key =null;
  24. For (String k:keys) {
  25. Key=k;
  26. Break ;
  27. }
  28. Integer i =null;
  29. if (key!=null) {
  30. I= (Integer) resultmap.get (key);
  31. }
  32. if (i!=null) {
  33. //FINAL result
  34. Re+=i;
  35. }
  36. if (key!=null) {
  37. //Remove items that have already been calculated
  38. Resultmap.remove (key);
  39. }
  40. }
  41. }
  42. }

Three, Summary:

Master-worker mode is a method of parallelization of serial tasks, the decomposed subtasks can be processed in parallel in the system, and if necessary, the master process does not have to wait for all subtasks to complete the calculation, it can calculate the final result set according to the existing partial result set.

Ext.: http://blog.csdn.net/lmdcszh/article/details/39698189

Multithreading: Multithreaded design Mode (iii): Master-worker mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.