Merge branch 'cecil-light'
[mono.git] / mcs / class / System.Core / System.Linq.Parallel / ParallelExecuter.cs
1 //
2 // ParallelExecuter.cs
3 //
4 // Author:
5 //       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
6 //
7 // Copyright (c) 2010 Jérémie "Garuma" Laval
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
15 //
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
18 //
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 // THE SOFTWARE.
26
27 #if NET_4_0
28 using System;
29 using System.Threading;
30 using System.Threading.Tasks;
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.Concurrent;
34 using System.Linq.Parallel.QueryNodes;
35
36 namespace System.Linq.Parallel
37 {
38         internal static class ParallelExecuter
39         {
40                 internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode)
41                 {
42                         return CheckQuery<T> (startingNode, false);
43                 }
44
45                 internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode, bool blocking)
46                 {
47                         return CheckQuery (startingNode, GetBestWorkerNumber (blocking));
48                 }
49
50                 internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode, int partitionCount)
51                 {
52                         QueryCheckerVisitor visitor = new QueryCheckerVisitor (partitionCount);
53                         startingNode.Visit (visitor);
54
55                         return visitor.Options;
56                 }
57
58                 internal static CancellationToken Chain (this CancellationToken self, CancellationTokenSource other)
59                 {
60                         CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource (self, other.Token);
61                         return linked.Token;
62                 }
63
64                 internal static bool IsOrdered<TSource> (this QueryBaseNode<TSource> source)
65                 {
66                         QueryIsOrderedVisitor visitor = new QueryIsOrderedVisitor ();
67                         source.Visit (visitor);
68
69                         return visitor.BehindOrderGuard;
70                 }
71
72                 internal static int GetBestWorkerNumber ()
73                 {
74                         return GetBestWorkerNumber (false);
75                 }
76
77                 internal static int GetBestWorkerNumber (bool blocking)
78                 {
79                         return blocking ? Environment.ProcessorCount + 1 : Environment.ProcessorCount;
80                 }
81
82                 internal static Task[] Process<TSource, TElement> (QueryBaseNode<TSource> node,
83                                                                    Action<TElement, CancellationToken> call,
84                                                                    Func<QueryBaseNode<TSource>, QueryOptions, IList<IEnumerable<TElement>>> acquisitionFunc,
85                                                                    QueryOptions options)
86                 {
87                         return Process<TSource, TElement> (node, call, acquisitionFunc, null, options);
88                 }
89
90                 internal static Task[] Process<TSource, TElement> (QueryBaseNode<TSource> node,
91                                                                    Action<TElement, CancellationToken> call,
92                                                                    Func<QueryBaseNode<TSource>, QueryOptions, IList<IEnumerable<TElement>>> acquisitionFunc,
93                                                                    Action endAction,
94                                                                    QueryOptions options)
95                 {
96                         CancellationTokenSource src
97                                 = CancellationTokenSource.CreateLinkedTokenSource (options.ImplementerToken, options.Token);
98
99                         IList<IEnumerable<TElement>> enumerables = acquisitionFunc (node, options);
100
101                         Task[] tasks = new Task[enumerables.Count];
102
103                         for (int i = 0; i < tasks.Length; i++) {
104                                 int index = i;
105                                 tasks[i] = Task.Factory.StartNew (() => {
106                                         foreach (TElement item in enumerables[index]) {
107                                                 // This is from specific operators
108                                                 if (options.ImplementerToken.IsCancellationRequested)
109                                                         break;
110                                                 if (options.Token.IsCancellationRequested)
111                                                         throw new OperationCanceledException (options.Token);
112
113                                                 call (item, src.Token);
114                                         }
115                                         if (endAction != null)
116                                                 endAction ();
117                                   }, options.Token);
118                         }
119
120                         return tasks;
121                 }
122
123                 internal static void ProcessAndBlock<T> (QueryBaseNode<T> node, Action<T, CancellationToken> call)
124                 {
125                         QueryOptions options = CheckQuery (node, true);
126
127                         Task[] tasks = Process (node, call, (n, o) => n.GetEnumerables (o), options);
128                         Task.WaitAll (tasks, options.Token);
129                 }
130
131                 internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<T, CancellationToken> call,
132                                                               Action callback, QueryOptions options)
133                 {
134                         Task[] tasks = Process (node, call, (n, o) => n.GetEnumerables (o), options);
135                         if (callback != null)
136                                 Task.Factory.ContinueWhenAll (tasks,  (_) => callback ());
137
138                         return () => Task.WaitAll (tasks, options.Token);
139                 }
140
141                 internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<KeyValuePair<long, T>, CancellationToken> call,
142                                                               Action endAction,
143                                                               Action callback, QueryOptions options)
144                 {
145                         Task[] tasks = Process (node, call, (n, o) => n.GetOrderedEnumerables (o), endAction, options);
146                         if (callback != null)
147                                 Task.Factory.ContinueWhenAll (tasks,  (_) => callback ());
148
149                         return () => Task.WaitAll (tasks, options.Token);
150                 }
151
152                 internal static void ProcessAndAggregate<T, U> (QueryBaseNode<T> node,
153                                                                 Func<U> seedFunc,
154                                                                 Func<U, T, U> localCall,
155                                                                 Action<IList<U>> call)
156                 {
157                         QueryOptions options = CheckQuery (node, true);
158
159                         IList<IEnumerable<T>> enumerables = node.GetEnumerables (options);
160                         U[] locals = new U[enumerables.Count];
161                         Task[] tasks = new Task[enumerables.Count];
162
163                         if (seedFunc != null) {
164                                 for (int i = 0; i < locals.Length; i++)
165                                         locals[i] = seedFunc ();
166                         }
167
168                         for (int i = 0; i < tasks.Length; i++) {
169                                 var procSlot = new AggregateProcessSlot<T, U> (options,
170                                                                                i,
171                                                                                enumerables[i].GetEnumerator (),
172                                                                                locals,
173                                                                                localCall,
174                                                                                seedFunc);
175
176                                 tasks[i] = Task.Factory.StartNew (procSlot.Process, options.Token);
177                         }
178
179                         Task.WaitAll (tasks, options.Token);
180
181                         if (call != null)
182                                 call (locals);
183                 }
184
185                 class AggregateProcessSlot<T, U>
186                 {
187                         readonly QueryOptions options;
188                         readonly int index;
189                         readonly IEnumerator<T> enumerator;
190                         readonly U[] locals;
191                         readonly Func<U, T, U> localCall;
192                         readonly Func<U> seedFunc;
193
194                         public AggregateProcessSlot (QueryOptions options,
195                                                      int index,
196                                                      IEnumerator<T> enumerator,
197                                                      U[] locals,
198                                                      Func<U, T, U> localCall,
199                                                      Func<U> seedFunc)
200                         {
201                                 this.options = options;
202                                 this.index = index;
203                                 this.enumerator = enumerator;
204                                 this.locals = locals;
205                                 this.localCall = localCall;
206                                 this.seedFunc = seedFunc;
207                         }
208
209                         public void Process ()
210                         {
211                                 var token = options.Token;
212                                 var implementerToken = options.ImplementerToken;
213
214                                 try {
215                                         if (seedFunc == null) {
216                                                 if (!enumerator.MoveNext ())
217                                                         return;
218                                                 locals[index] = (U)(object)enumerator.Current;
219                                         }
220
221                                         while (enumerator.MoveNext ()) {
222                                                 if (implementerToken.IsCancellationRequested)
223                                                         break;
224                                                 token.ThrowIfCancellationRequested ();
225                                                 locals[index] = localCall (locals[index], enumerator.Current);
226                                         }
227                                 } finally {
228                                         enumerator.Dispose ();
229                                 }
230                         }
231                 }
232         }
233 }
234 #endif