Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.ParallelEngine/3.3/ParallelEngine.cs @ 9323

Last change on this file since 9323 was 9323, checked in by mkommend, 10 years ago

#2024: Changed parallel engine to use parallel.foreach instead of spawning task manually to enable more options for parallelization.

File size: 5.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Threading;
25using System.Threading.Tasks;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.ParallelEngine {
31  /// <summary>
32  /// Represents an engine that executes its steps in parallel (if possible) using multiple threads.
33  /// This engine is suitable for parallel processing on shared memory systems which provide multiple cores.
34  /// </summary>
35  [StorableClass]
36  [Item("Parallel Engine", "Engine for parallel execution of algorithms using multiple threads (suitable for shared memory systems with multiple cores).")]
37  public class ParallelEngine : Engine {
38    private CancellationToken cancellationToken;
39    private ParallelOptions parallelOptions;
40
41    [Storable(DefaultValue = -1)]
42    private int degreeOfParallelism;
43    public int DegreeOfParallelism {
44      get { return degreeOfParallelism; }
45      set {
46        if (degreeOfParallelism != value) {
47          degreeOfParallelism = value;
48          OnDegreeOfParallelismChanged();
49        }
50      }
51    }
52
53    [StorableConstructor]
54    protected ParallelEngine(bool deserializing) : base(deserializing) { }
55    protected ParallelEngine(ParallelEngine original, Cloner cloner)
56      : base(original, cloner) {
57      this.DegreeOfParallelism = original.DegreeOfParallelism;
58    }
59    public ParallelEngine() : base() { }
60
61    public override IDeepCloneable Clone(Cloner cloner) {
62      return new ParallelEngine(this, cloner);
63    }
64
65    public event EventHandler DegreeOfParallelismChanged;
66    protected void OnDegreeOfParallelismChanged() {
67      var handler = DegreeOfParallelismChanged;
68      if (handler != null) handler(this, EventArgs.Empty);
69    }
70
71
72    protected override void Run(CancellationToken cancellationToken) {
73      this.cancellationToken = cancellationToken;
74      parallelOptions = new ParallelOptions();
75      parallelOptions.MaxDegreeOfParallelism = DegreeOfParallelism;
76      Run(ExecutionStack);
77    }
78
79    private void Run(object state) {
80      Stack<IOperation> executionStack = (Stack<IOperation>)state;
81      IOperation next;
82      OperationCollection coll;
83      IAtomicOperation operation;
84
85      while (executionStack.Count > 0) {
86        cancellationToken.ThrowIfCancellationRequested();
87
88        next = executionStack.Pop();
89        if (next is OperationCollection) {
90          coll = (OperationCollection)next;
91          if (coll.Parallel) {
92            Stack<IOperation>[] stacks = new Stack<IOperation>[coll.Count];
93            for (int i = 0; i < coll.Count; i++) {
94              stacks[i] = new Stack<IOperation>();
95              stacks[i].Push(coll[i]);
96            }
97            try {
98              Parallel.ForEach(stacks, parallelOptions, Run);
99            }
100            catch (AggregateException ex) {
101              OperationCollection remaining = new OperationCollection() { Parallel = true };
102              for (int i = 0; i < stacks.Length; i++) {
103                if (stacks[i].Count == 1)
104                  remaining.Add(stacks[i].Pop());
105                if (stacks[i].Count > 1) {
106                  OperationCollection ops = new OperationCollection();
107                  while (stacks[i].Count > 0)
108                    ops.Add(stacks[i].Pop());
109                  remaining.Add(ops);
110                }
111              }
112              if (remaining.Count > 0) executionStack.Push(remaining);
113              throw ex;
114            }
115          } else {
116            for (int i = coll.Count - 1; i >= 0; i--)
117              if (coll[i] != null) executionStack.Push(coll[i]);
118          }
119        } else if (next is IAtomicOperation) {
120          operation = (IAtomicOperation)next;
121          try {
122            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
123          }
124          catch (Exception ex) {
125            executionStack.Push(operation);
126            if (ex is OperationCanceledException) throw ex;
127            else throw new OperatorExecutionException(operation.Operator, ex);
128          }
129          if (next != null) executionStack.Push(next);
130
131          if (operation.Operator.Breakpoint) {
132            string message = string.Format("Breakpoint: {0}", operation.Operator.Name != string.Empty ? operation.Operator.Name : operation.Operator.ItemName);
133            Log.LogMessage(message);
134            throw new OperationCanceledException(message);
135          }
136        }
137      }
138    }
139  }
140}
Note: See TracBrowser for help on using the repository browser.