-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreading.cs
More file actions
487 lines (386 loc) · 15.4 KB
/
Copy pathThreading.cs
File metadata and controls
487 lines (386 loc) · 15.4 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#pragma warning disable 0420
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using JSIL.Internal;
#if TARGETTING_FX_4_5 && false
using WeakTrackedLockReference = System.WeakReference<TrackedLock>;
#else
using WeakTrackedLockReference = System.WeakReference;
#endif
namespace JSIL.Threading {
public class TrackedLockCollection : IDisposable {
public class DeadlockInfo {
public readonly TrackedLock A, B;
public DeadlockInfo (TrackedLock a, TrackedLock b) {
A = a;
B = b;
}
public override string ToString () {
return String.Format("[{0}, {1}]", A, B);
}
}
public class Wait : IDisposable {
private readonly ManualResetEventSlim Signal = new ManualResetEventSlim(false);
private readonly TrackedLockCollection Collection;
public readonly TrackedLock Lock;
public readonly Thread Thread;
public Wait (TrackedLockCollection collection, TrackedLock lck, Thread thread) {
Collection = collection;
Lock = lck;
Thread = thread;
if (!Collection.WaitsByThread.TryAdd(thread, this))
throw new ThreadStateException();
}
internal bool IsSignaled {
get {
return Signal.IsSet;
}
}
public bool Block (int timeoutMs = -1) {
if (timeoutMs >= 0) {
return Signal.Wait(timeoutMs);
} else {
Signal.Wait();
return true;
}
}
public void Wake () {
Signal.Set();
}
public void Dispose () {
Signal.Dispose();
OrderedDictionary<Wait, bool> waits;
if (!Collection.Waits.TryGet(Lock, out waits))
throw new ThreadStateException();
lock (waits)
waits.Remove(this);
Wait temp;
if (!Collection.WaitsByThread.TryRemove(Thread, out temp))
throw new ThreadStateException();
}
}
protected readonly ConcurrentDictionary<WeakTrackedLockReference, bool> Locks = new ConcurrentDictionary<WeakTrackedLockReference, bool>(
new ReferenceComparer<WeakTrackedLockReference>()
);
protected readonly ConcurrentDictionary<Thread, Wait> WaitsByThread = new ConcurrentDictionary<Thread, Wait>(
new Internal.ReferenceComparer<Thread>()
);
protected readonly ConcurrentCache<TrackedLock, OrderedDictionary<Wait, bool>> Waits = new ConcurrentCache<TrackedLock, OrderedDictionary<Wait, bool>>(
new ReferenceComparer<TrackedLock>()
);
private static readonly ConcurrentCache<TrackedLock, OrderedDictionary<Wait, bool>>.CreatorFunction MakeWaitList;
static TrackedLockCollection () {
MakeWaitList = (lck) => new OrderedDictionary<Wait, bool>();
}
internal void Track (WeakTrackedLockReference weakLock) {
var lck = (TrackedLock)weakLock.Target;
if (!Locks.TryAdd(weakLock, false))
throw new ThreadStateException();
}
internal void Untrack (WeakTrackedLockReference weakLock) {
var lck = (TrackedLock)weakLock.Target;
if (lck == null)
return;
bool temp;
if (!Locks.TryRemove(weakLock, out temp))
throw new ThreadStateException();
OrderedDictionary<Wait, bool> waits;
if (Waits.TryGet(lck, out waits)) {
lock (waits) {
foreach (var w in waits)
w.Key.Dispose();
waits.Clear();
}
if (!Waits.TryRemove(lck))
throw new ThreadStateException();
}
}
public DeadlockInfo DetectDeadlock (Wait wait) {
var seenLocks = new HashSet<TrackedLock>(new Internal.ReferenceComparer<TrackedLock>());
var waitToExamine = wait;
while (waitToExamine != null) {
seenLocks.Add(waitToExamine.Lock);
var ownerThread = waitToExamine.Lock.HeldBy;
if (ownerThread == null)
break;
Wait nextWaitToExamine;
if (!WaitsByThread.TryGetValue(ownerThread, out nextWaitToExamine))
break;
if (seenLocks.Contains(nextWaitToExamine.Lock))
return new DeadlockInfo(waitToExamine.Lock, nextWaitToExamine.Lock);
waitToExamine = nextWaitToExamine;
}
return null;
}
internal bool TryCreateWait (WeakTrackedLockReference weakLock, out DeadlockInfo deadlock, out Wait wait) {
var lck = (TrackedLock)weakLock.Target;
if (lck == null) {
wait = default(Wait);
deadlock = default(DeadlockInfo);
return false;
}
var currentThread = Thread.CurrentThread;
var waits = Waits.GetOrCreate(lck, MakeWaitList);
wait = new Wait(this, lck, currentThread);
lock (waits)
waits.Enqueue(wait, false);
deadlock = DetectDeadlock(wait);
if (deadlock != null) {
lock (waits)
waits.Remove(wait);
var wasSignaled = wait.IsSignaled;
wait.Dispose();
wait = null;
// It's possible, albeit incredibly unlikely, for someone to call Wake on our wait
// before we do the deadlock check.
// If this happens, try to dequeue another wait from the queue and wake it up in our stead.
// This can probably still break, though...
if (wasSignaled) {
if (TryDequeueOneWait(lck, out wait))
wait.Wake();
}
return false;
}
return true;
}
internal bool TryDequeueOneWait (TrackedLock lck, out Wait wait) {
wait = null;
OrderedDictionary<Wait, bool> waits;
if (!Waits.TryGet(lck, out waits))
return false;
bool temp;
lock (waits)
return waits.TryDequeueFirst(out wait, out temp);
}
public void Dispose () {
Locks.Clear();
Waits.Clear();
}
internal int GetWaitingThreadCount (WeakTrackedLockReference weakLock) {
var lck = (TrackedLock)weakLock.Target;
if (lck == null)
return 0;
OrderedDictionary<Wait, bool> waits;
if (!Waits.TryGet(lck, out waits))
return 0;
lock (waits)
return waits.Count;
}
}
public class TrackedLock : IDisposable {
public readonly WeakTrackedLockReference WeakSelf;
public readonly TrackedLockCollection Collection;
public readonly Func<string> GetName;
private volatile bool _IsTracked = false;
private volatile int _RecursionCount = 0;
private volatile Thread _HeldBy = null;
public TrackedLock (TrackedLockCollection collection, string name)
: this(collection, () => name) {
}
public TrackedLock (TrackedLockCollection collection, Func<string> getName = null) {
Collection = collection;
GetName = getName;
WeakSelf = new WeakTrackedLockReference(this);
}
public void Dispose () {
if (IsDisposed)
return;
// FIXME
_HeldBy = null;
IsDisposed = true;
if (_IsTracked)
Collection.Untrack(WeakSelf);
}
public bool IsDisposed {
get;
private set;
}
public Thread HeldBy {
get {
return _HeldBy;
}
}
public bool IsHeld {
get {
return _HeldBy != null;
}
}
public int RecursionDepth {
get {
return _RecursionCount;
}
}
public int WaitingThreadCount {
get {
return Collection.GetWaitingThreadCount(WeakSelf);
}
}
private void EnsureTracked () {
if (!_IsTracked) {
lock (this) {
if (!_IsTracked) {
Collection.Track(WeakSelf);
_IsTracked = true;
}
}
}
}
public TrackedLockResult TryEnter (out Thread previousOwner, bool recursive = false) {
var currentThread = Thread.CurrentThread;
previousOwner = Interlocked.CompareExchange(ref _HeldBy, currentThread, null);
var acquired = previousOwner == null;
TrackedLockFailureReason? failureReason = null;
if (!acquired) {
failureReason = (previousOwner == currentThread)
? TrackedLockFailureReason.HeldByCurrentThread
: TrackedLockFailureReason.HeldByOtherThread;
}
if (recursive && (failureReason == TrackedLockFailureReason.HeldByCurrentThread)) {
_RecursionCount += 1;
return new TrackedLockResult();
}
var result = new TrackedLockResult(failureReason);
#if LOCK_TRACING
Console.WriteLine(
"TryEnter {0} => {1}; result = {2}",
previousOwner != null ? previousOwner.Name : "<null>",
_HeldBy != null ? _HeldBy.Name : "<null>",
result
);
#endif
return result;
}
public TrackedLockResult TryEnter (bool recursive = false) {
Thread temp;
return TryEnter(out temp, recursive);
}
public TrackedLockResult TryBlockingEnter (bool recursive = false, int timeoutMs = -1) {
TrackedLockCollection.DeadlockInfo temp;
return TryBlockingEnter(out temp, recursive, timeoutMs);
}
public TrackedLockResult TryBlockingEnter (out TrackedLockCollection.DeadlockInfo deadlock, bool recursive = false, int timeoutMs = -1) {
bool iterating = true;
TrackedLockCollection.Wait wait;
deadlock = null;
while (iterating) {
var result = TryEnter(recursive);
if (result.FailureReason != TrackedLockFailureReason.HeldByOtherThread)
return result;
EnsureTracked();
if (Collection.TryCreateWait(WeakSelf, out deadlock, out wait)) {
using (wait) {
result = TryEnter(recursive);
if (result.FailureReason == TrackedLockFailureReason.HeldByOtherThread) {
var finishedWaiting = wait.Block(timeoutMs);
if (!finishedWaiting)
iterating = false;
} else {
return result;
}
}
} else {
return new TrackedLockResult(TrackedLockFailureReason.Deadlock);
}
}
return new TrackedLockResult(TrackedLockFailureReason.HeldByOtherThread);
}
public void BlockingEnter (bool recursive = false, int timeoutMs = -1) {
EnsureTracked();
TrackedLockCollection.DeadlockInfo deadlock;
var result = TryBlockingEnter(out deadlock, recursive, timeoutMs);
if (!result.Success) {
switch (result.FailureReason) {
case TrackedLockFailureReason.HeldByCurrentThread:
throw new LockAlreadyHeldException();
case TrackedLockFailureReason.Deadlock:
throw new DeadlockAvertedException(deadlock.A, deadlock.B);
}
}
}
public void Exit () {
var currentThread = Thread.CurrentThread;
bool released = false;
if (_HeldBy == currentThread) {
if (_RecursionCount == 0) {
EnsureTracked();
TrackedLockCollection.Wait wait;
if (!Collection.TryDequeueOneWait(this, out wait))
wait = null;
var previousOwner = Interlocked.CompareExchange(ref _HeldBy, null, currentThread);
released = previousOwner == currentThread;
#if LOCK_TRACING
Console.WriteLine(
"Exit {0} => {1}; released = {2}",
previousOwner != null ? previousOwner.Name : "<null>",
_HeldBy != null ? _HeldBy.Name : "<null>",
released
);
#endif
if (!released)
throw new InvalidOperationException("Lock not held");
if (wait != null)
wait.Wake();
} else {
_RecursionCount -= 1;
released = false;
}
} else {
throw new InvalidOperationException("Lock held by other thread or not held");
}
}
public override string ToString () {
var hby = _HeldBy;
return String.Format(
"<TrackedLock '{0}' held by {1}>",
(GetName != null)
? GetName()
: String.Format("Unnamed {0}", GetHashCode()),
hby != null
? String.Format("thread #{0} '{1}'", hby.ManagedThreadId, hby.Name)
: "nobody"
);
}
}
public enum TrackedLockFailureReason {
HeldByCurrentThread,
HeldByOtherThread,
Deadlock
}
public struct TrackedLockResult {
public readonly TrackedLockFailureReason? FailureReason;
public TrackedLockResult (TrackedLockFailureReason? failureReason) {
FailureReason = failureReason;
}
public bool Success {
get {
return !FailureReason.HasValue;
}
}
public static explicit operator bool (TrackedLockResult result) {
return result.Success;
}
public override string ToString () {
if (FailureReason.HasValue)
return FailureReason.Value.ToString();
else
return "Success";
}
}
public class LockAlreadyHeldException : Exception {
public LockAlreadyHeldException ()
: base("The current thread already holds this lock.") {
}
}
public class DeadlockAvertedException : Exception {
public TrackedLock Lock1, Lock2;
public DeadlockAvertedException (TrackedLock lock1, TrackedLock lock2)
: base("The operation would have caused a deadlock.") {
Lock1 = lock1;
Lock2 = lock2;
}
}
}