Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5959 was 5445, checked in by swagner, 14 years ago

Updated year of copyrights (#1406)

File size: 4.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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
40    [StorableConstructor]
41    protected ParallelEngine(bool deserializing) : base(deserializing) { }
42    protected ParallelEngine(ParallelEngine original, Cloner cloner) : base(original, cloner) { }
43    public ParallelEngine() : base() { }
44
45    public override IDeepCloneable Clone(Cloner cloner) {
46      return new ParallelEngine(this, cloner);
47    }
48
49    protected override void Run(CancellationToken cancellationToken) {
50      this.cancellationToken = cancellationToken;
51      Run(ExecutionStack);
52    }
53
54    private void Run(object state) {
55      Stack<IOperation> executionStack = (Stack<IOperation>)state;
56      IOperation next;
57      OperationCollection coll;
58      IAtomicOperation operation;
59
60      while (executionStack.Count > 0) {
61        cancellationToken.ThrowIfCancellationRequested();
62
63        next = executionStack.Pop();
64        if (next is OperationCollection) {
65          coll = (OperationCollection)next;
66          if (coll.Parallel) {
67            Task[] tasks = new Task[coll.Count];
68            Stack<IOperation>[] stacks = new Stack<IOperation>[coll.Count];
69            for (int i = 0; i < coll.Count; i++) {
70              stacks[i] = new Stack<IOperation>();
71              stacks[i].Push(coll[i]);
72              tasks[i] = Task.Factory.StartNew(Run, stacks[i], cancellationToken);
73            }
74            try {
75              Task.WaitAll(tasks);
76            }
77            catch (AggregateException ex) {
78              OperationCollection remaining = new OperationCollection() { Parallel = true };
79              for (int i = 0; i < stacks.Length; i++) {
80                if (stacks[i].Count == 1)
81                  remaining.Add(stacks[i].Pop());
82                if (stacks[i].Count > 1) {
83                  OperationCollection ops = new OperationCollection();
84                  while (stacks[i].Count > 0)
85                    ops.Add(stacks[i].Pop());
86                  remaining.Add(ops);
87                }
88              }
89              if (remaining.Count > 0) executionStack.Push(remaining);
90              throw ex;
91            }
92          } else {
93            for (int i = coll.Count - 1; i >= 0; i--)
94              if (coll[i] != null) executionStack.Push(coll[i]);
95          }
96        } else if (next is IAtomicOperation) {
97          operation = (IAtomicOperation)next;
98          try {
99            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
100          }
101          catch (Exception ex) {
102            executionStack.Push(operation);
103            if (ex is OperationCanceledException) throw ex;
104            else throw new OperatorExecutionException(operation.Operator, ex);
105          }
106          if (next != null) executionStack.Push(next);
107
108          if (operation.Operator.Breakpoint) {
109            string message = string.Format("Breakpoint: {0}", operation.Operator.Name != string.Empty ? operation.Operator.Name : operation.Operator.ItemName);
110            Log.LogMessage(message);
111            throw new OperationCanceledException(message);
112          }
113        }
114      }
115    }
116  }
117}
Note: See TracBrowser for help on using the repository browser.