1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
|
#if NET_4_0
// ThreadWorker.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Threading;
using System.Collections.Concurrent;
namespace System.Threading.Tasks
{
internal class ThreadWorker: IDisposable
{
static Random r = new Random ();
Thread workerThread;
readonly ThreadWorker[] others;
internal readonly IDequeOperations<Task> dDeque;
readonly IProducerConsumerCollection<Task> sharedWorkQueue;
readonly Action<Task> childWorkAdder;
// Flag to tell if workerThread is running
int started = 0;
readonly bool isLocal;
readonly int workerLength;
readonly int stealingStart;
const int maxRetry = 5;
#region Sleep related fields
readonly SpinWait wait = new SpinWait ();
const int sleepThreshold = 100000;
#endregion
Action threadInitializer;
public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
int maxStackSize, ThreadPriority priority)
: this (sched, others, sharedWorkQueue, true, maxStackSize, priority)
{
}
public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
bool createThread, int maxStackSize, ThreadPriority priority)
{
this.others = others;
// if (!string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("USE_CYCLIC"))) {
// Console.WriteLine ("Using cyclic deque");
// this.dDeque = new CyclicDeque<Task> ();
// } else {
// this.dDeque = new DynamicDeque<Task> ();
// }
this.dDeque = new CyclicDeque<Task> ();
this.sharedWorkQueue = sharedWorkQueue;
this.workerLength = others.Length;
this.isLocal = !createThread;
this.childWorkAdder = delegate (Task t) {
dDeque.PushBottom (t);
sched.PulseAll ();
};
// Find the stealing start index randomly (then the traversal
// will be done in Round-Robin fashion)
do {
this.stealingStart = r.Next(0, workerLength);
} while (others[stealingStart] == this);
InitializeUnderlyingThread (maxStackSize, priority);
}
void InitializeUnderlyingThread (int maxStackSize, ThreadPriority priority)
{
threadInitializer = delegate {
// Special case of the participant ThreadWorker
if (isLocal) {
this.workerThread = Thread.CurrentThread;
return;
}
this.workerThread = (maxStackSize == 0) ? new Thread (WorkerMethodWrapper) :
new Thread (WorkerMethodWrapper, maxStackSize);
this.workerThread.IsBackground = true;
this.workerThread.Priority = priority;
};
threadInitializer ();
}
public void Dispose ()
{
Stop ();
if (!isLocal && workerThread.ThreadState != ThreadState.Stopped)
workerThread.Abort ();
}
public void Pulse ()
{
// If the thread was stopped then set it in use and restart it
int result = Interlocked.Exchange (ref started, 1);
if (result != 0)
return;
if (!isLocal) {
if (this.workerThread.ThreadState != ThreadState.Unstarted) {
threadInitializer ();
}
workerThread.Start ();
}
}
public void Stop ()
{
// Set the flag to stop so that the while in the thread will stop
// doing its infinite loop.
started = 0;
}
// This is the actual method called in the Thread
void WorkerMethodWrapper ()
{
int sleepTime = 0;
// Main loop
while (started == 1) {
bool result = false;
try {
result = WorkerMethod ();
} catch (Exception e) {
Console.WriteLine (e.ToString ());
}
// Wait a little and if the Thread has been more sleeping than working shut it down
wait.SpinOnce ();
if (result)
sleepTime = 0;
if (sleepTime++ > sleepThreshold)
break;
}
started = 0;
}
// Main method, used to do all the logic of retrieving, processing and stealing work.
bool WorkerMethod ()
{
bool result = false;
bool hasStolenFromOther;
do {
hasStolenFromOther = false;
Task value;
// We fill up our work deque concurrently with other ThreadWorker
while (sharedWorkQueue.Count > 0) {
while (sharedWorkQueue.TryTake (out value)) {
dDeque.PushBottom (value);
}
// Now we process our work
while (dDeque.PopBottom (out value) == PopResult.Succeed) {
if (value != null) {
value.Execute (childWorkAdder);
result = true;
}
}
}
// When we have finished, steal from other worker
ThreadWorker other;
// Repeat the operation a little so that we can let other things process.
for (int j = 0; j < maxRetry; j++) {
// Start stealing with the ThreadWorker at our right to minimize contention
for (int it = stealingStart; it < stealingStart + workerLength; it++) {
int i = it % workerLength;
if ((other = others [i]) == null || other == this)
continue;
// Maybe make this steal more than one item at a time, see TODO.
if (other.dDeque.PopTop (out value) == PopResult.Succeed) {
hasStolenFromOther = true;
if (value != null) {
value.Execute (childWorkAdder);
result = true;
}
}
}
}
} while (sharedWorkQueue.Count > 0 || hasStolenFromOther);
return result;
}
// Almost same as above but with an added predicate and treating one item at a time.
// It's used by Scheduler Participate(...) method for special waiting case like
// Task.WaitAll(someTasks) or Task.WaitAny(someTasks)
public static void WorkerMethod (Func<bool> predicate, IProducerConsumerCollection<Task> sharedWorkQueue,
ThreadWorker[] others)
{
while (!predicate ()) {
Task value;
// Dequeue only one item as we have restriction
if (sharedWorkQueue.TryTake (out value)) {
if (value != null) {
value.Execute (null);
}
}
// First check to see if we comply to predicate
if (predicate ()) {
return;
}
// Try to complete other work by stealing since our desired tasks may be in other worker
ThreadWorker other;
for (int i = 0; i < others.Length; i++) {
if ((other = others [i]) == null)
continue;
if (other.dDeque.PopTop (out value) == PopResult.Succeed) {
if (value != null) {
value.Execute (null);
}
}
if (predicate ()) {
return;
}
}
}
}
public bool Finished {
get {
return started == 0;
}
}
public bool IsLocal {
get {
return isLocal;
}
}
public int Id {
get {
return workerThread.ManagedThreadId;
}
}
public bool Equals (ThreadWorker other)
{
return (other == null) ? false : object.ReferenceEquals (this.dDeque, other.dDeque);
}
public override bool Equals (object obj)
{
ThreadWorker temp = obj as ThreadWorker;
return temp == null ? false : Equals (temp);
}
public override int GetHashCode ()
{
return workerThread.ManagedThreadId.GetHashCode ();
}
}
}
#endif
|