-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
MonitorTests.cs
513 lines (454 loc) · 19.9 KB
/
MonitorTests.cs
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public static class MonitorTests
{
private const int FailTimeoutMilliseconds = 30000;
// Attempts a single recursive acquisition/release cycle of a newly-created lock.
[Fact]
public static void BasicRecursion()
{
var obj = new object();
Assert.True(Monitor.TryEnter(obj));
Assert.True(Monitor.TryEnter(obj));
Monitor.Exit(obj);
Assert.True(Monitor.IsEntered(obj));
Monitor.Enter(obj);
Assert.True(Monitor.IsEntered(obj));
Monitor.Exit(obj);
Assert.True(Monitor.IsEntered(obj));
Monitor.Exit(obj);
Assert.False(Monitor.IsEntered(obj));
}
// Attempts to overflow the recursion count of a newly-created lock.
[Fact]
public static void DeepRecursion()
{
var obj = new object();
var hc = obj.GetHashCode();
// reduced from "(long)int.MaxValue + 2;" to something that will return in a more meaningful time
const int limit = 10000;
for (var i = 0L; i < limit; i++)
{
Assert.True(Monitor.TryEnter(obj));
}
for (var j = 0L; j < (limit - 1); j++)
{
Monitor.Exit(obj);
Assert.True(Monitor.IsEntered(obj));
}
Monitor.Exit(obj);
Assert.False(Monitor.IsEntered(obj));
}
[Fact]
public static void IsEntered()
{
var obj = new object();
Assert.False(Monitor.IsEntered(obj));
lock (obj)
{
Assert.True(Monitor.IsEntered(obj));
}
Assert.False(Monitor.IsEntered(obj));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void IsEntered_WhenHeldBySomeoneElse()
{
var obj = new object();
var b = new Barrier(2);
Task t = Task.Run(() =>
{
lock (obj)
{
b.SignalAndWait();
Assert.True(Monitor.IsEntered(obj));
b.SignalAndWait();
}
});
b.SignalAndWait();
Assert.False(Monitor.IsEntered(obj));
b.SignalAndWait();
t.Wait();
}
[Fact]
public static void Enter_SetsLockTaken()
{
bool lockTaken = false;
var obj = new object();
Monitor.Enter(obj, ref lockTaken);
Assert.True(lockTaken);
Monitor.Exit(obj);
Assert.True(lockTaken);
}
[Fact]
public static void Enter_Invalid()
{
bool lockTaken = false;
var obj = new object();
Assert.Throws<ArgumentNullException>(() => Monitor.Enter(null));
Assert.Throws<ArgumentNullException>(() => Monitor.Enter(null, ref lockTaken));
Assert.False(lockTaken);
lockTaken = true;
AssertExtensions.Throws<ArgumentException>("lockTaken", () => Monitor.Enter(obj, ref lockTaken));
Assert.True(lockTaken);
}
[Fact]
public static void Exit_Invalid()
{
var obj = new object();
int valueType = 1;
Assert.Throws<ArgumentNullException>(() => Monitor.Exit(null));
Assert.Throws<SynchronizationLockException>(() => Monitor.Exit(obj));
Assert.Throws<SynchronizationLockException>(() => Monitor.Exit(new object()));
Assert.Throws<SynchronizationLockException>(() => Monitor.Exit(valueType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Exit_WhenHeldBySomeoneElse_ThrowsSynchronizationLockException()
{
var obj = new object();
var b = new Barrier(2);
Task t = Task.Run(() =>
{
lock (obj)
{
b.SignalAndWait();
b.SignalAndWait();
}
});
b.SignalAndWait();
Assert.Throws<SynchronizationLockException>(() => Monitor.Exit(obj));
b.SignalAndWait();
t.Wait();
}
[Fact]
public static void IsEntered_Invalid()
{
var obj = new object();
AssertExtensions.Throws<ArgumentNullException>("obj", () => Monitor.IsEntered(null));
}
[Fact]
public static void Pulse_Invalid()
{
var obj = new object();
AssertExtensions.Throws<ArgumentNullException>("obj", () => Monitor.Pulse(null));
}
[Fact]
public static void PulseAll_Invalid()
{
var obj = new object();
AssertExtensions.Throws<ArgumentNullException>("obj", () => Monitor.PulseAll(null));
}
[Fact]
public static void TryEnter_SetsLockTaken()
{
bool lockTaken = false;
var obj = new object();
Monitor.TryEnter(obj, ref lockTaken);
Assert.True(lockTaken);
Monitor.Exit(obj);
Assert.True(lockTaken);
}
[Fact]
public static void TryEnter_Invalid()
{
bool lockTaken = false;
var obj = new object();
Assert.Throws<ArgumentNullException>(() => Monitor.TryEnter(null));
Assert.Throws<ArgumentNullException>(() => Monitor.TryEnter(null, ref lockTaken));
Assert.Throws<ArgumentNullException>(() => Monitor.TryEnter(null, 1));
Assert.Throws<ArgumentNullException>(() => Monitor.TryEnter(null, 1, ref lockTaken));
Assert.Throws<ArgumentNullException>(() => Monitor.TryEnter(null, TimeSpan.Zero));
Assert.Throws<ArgumentNullException>(() => Monitor.TryEnter(null, TimeSpan.Zero, ref lockTaken));
Assert.Throws<ArgumentOutOfRangeException>(() => Monitor.TryEnter(obj, -2));
Assert.Throws<ArgumentOutOfRangeException>(() => Monitor.TryEnter(obj, -2, ref lockTaken));
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"timeout", () => Monitor.TryEnter(obj, TimeSpan.FromMilliseconds(-2)));
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"timeout", () => Monitor.TryEnter(obj, TimeSpan.FromMilliseconds(-2), ref lockTaken));
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"timeout",
() => Monitor.TryEnter(obj, TimeSpan.FromMilliseconds((double)int.MaxValue + 1)));
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"timeout",
() => Monitor.TryEnter(obj, TimeSpan.FromMilliseconds((double)int.MaxValue + 1), ref lockTaken));
lockTaken = true;
AssertExtensions.Throws<ArgumentException>("lockTaken", () => Monitor.TryEnter(obj, ref lockTaken));
Assert.True(lockTaken);
AssertExtensions.Throws<ArgumentException>("lockTaken", () => Monitor.TryEnter(obj, 0, ref lockTaken));
Assert.True(lockTaken);
AssertExtensions.Throws<ArgumentException>("lockTaken", () => Monitor.TryEnter(obj, TimeSpan.Zero, ref lockTaken));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Enter_HasToWait()
{
var thinLock = new object();
var awareLock = new object();
// Actually transition the aware lock to an aware lock by having a background thread wait for a lock
{
Action waitForThread;
Thread t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
Assert.False(Monitor.TryEnter(awareLock, ThreadTestHelpers.ExpectedTimeoutMilliseconds)));
t.IsBackground = true;
lock (awareLock)
{
t.Start();
waitForThread();
}
}
// When the current thread has the lock, have background threads wait for the lock in various ways. After a short
// duration, release the lock and allow the background threads to acquire the lock.
{
var backgroundTestDelegates = new List<Action<object>>();
Barrier readyBarrier = null;
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
Monitor.Enter(lockObj);
Monitor.Exit(lockObj);
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
bool lockTaken = false;
Monitor.Enter(lockObj, ref lockTaken);
Assert.True(lockTaken);
Monitor.Exit(lockObj);
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
lock (lockObj)
{
}
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
Assert.True(Monitor.TryEnter(lockObj, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Monitor.Exit(lockObj);
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
Assert.True(
Monitor.TryEnter(lockObj, TimeSpan.FromMilliseconds(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)));
Monitor.Exit(lockObj);
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
bool lockTaken = false;
Monitor.TryEnter(lockObj, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, ref lockTaken);
Assert.True(lockTaken);
Monitor.Exit(lockObj);
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
bool lockTaken = false;
Monitor.TryEnter(
lockObj,
TimeSpan.FromMilliseconds(ThreadTestHelpers.UnexpectedTimeoutMilliseconds),
ref lockTaken);
Assert.True(lockTaken);
Monitor.Exit(lockObj);
});
int testCount = backgroundTestDelegates.Count * 2; // two iterations each, one for thin lock and one for aware lock
readyBarrier = new Barrier(testCount + 1); // plus main thread
var waitForThreadArray = new Action[testCount];
for (int i = 0; i < backgroundTestDelegates.Count; ++i)
{
int icopy = i; // for use in delegates
Thread t =
ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i * 2],
() => backgroundTestDelegates[icopy](thinLock));
t.IsBackground = true;
t.Start();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i * 2 + 1],
() => backgroundTestDelegates[icopy](awareLock));
t.IsBackground = true;
t.Start();
}
lock (thinLock)
{
lock (awareLock)
{
readyBarrier.SignalAndWait(ThreadTestHelpers.UnexpectedTimeoutMilliseconds);
Thread.Sleep(ThreadTestHelpers.ExpectedTimeoutMilliseconds);
}
}
foreach (Action waitForThread in waitForThreadArray)
waitForThread();
}
// When the current thread has the lock, have background threads wait for the lock in various ways and time out
// after a short duration
{
var backgroundTestDelegates = new List<Action<object>>();
Barrier readyBarrier = null;
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
Assert.False(Monitor.TryEnter(lockObj, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
Assert.False(
Monitor.TryEnter(lockObj, TimeSpan.FromMilliseconds(ThreadTestHelpers.ExpectedTimeoutMilliseconds)));
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
bool lockTaken = false;
Monitor.TryEnter(lockObj, ThreadTestHelpers.ExpectedTimeoutMilliseconds, ref lockTaken);
Assert.False(lockTaken);
});
backgroundTestDelegates.Add(lockObj =>
{
readyBarrier.SignalAndWait();
bool lockTaken = false;
Monitor.TryEnter(
lockObj,
TimeSpan.FromMilliseconds(ThreadTestHelpers.ExpectedTimeoutMilliseconds),
ref lockTaken);
Assert.False(lockTaken);
});
int testCount = backgroundTestDelegates.Count * 2; // two iterations each, one for thin lock and one for aware lock
readyBarrier = new Barrier(testCount + 1); // plus main thread
var waitForThreadArray = new Action[testCount];
for (int i = 0; i < backgroundTestDelegates.Count; ++i)
{
int icopy = i; // for use in delegates
Thread t =
ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i * 2],
() => backgroundTestDelegates[icopy](thinLock));
t.IsBackground = true;
t.Start();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i * 2 + 1],
() => backgroundTestDelegates[icopy](awareLock));
t.IsBackground = true;
t.Start();
}
lock (thinLock)
{
lock (awareLock)
{
readyBarrier.SignalAndWait(ThreadTestHelpers.UnexpectedTimeoutMilliseconds);
foreach (Action waitForThread in waitForThreadArray)
waitForThread();
}
}
}
}
[Fact]
public static void Wait_Invalid()
{
var obj = new object();
Assert.Throws<ArgumentNullException>(() => Monitor.Wait(null));
Assert.Throws<ArgumentNullException>(() => Monitor.Wait(null, 1));
Assert.Throws<ArgumentNullException>(() => Monitor.Wait(null, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(() => Monitor.Wait(obj, -2));
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"timeout",
() => Monitor.Wait(obj, TimeSpan.FromMilliseconds(-2)));
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"timeout",
() => Monitor.Wait(obj, TimeSpan.FromMilliseconds((double)int.MaxValue + 1)));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void WaitTest()
{
var obj = new object();
var waitTests =
new Func<bool>[]
{
() => Monitor.Wait(obj, FailTimeoutMilliseconds, false),
() => Monitor.Wait(obj, FailTimeoutMilliseconds, true),
() => Monitor.Wait(obj, TimeSpan.FromMilliseconds(FailTimeoutMilliseconds), false),
() => Monitor.Wait(obj, TimeSpan.FromMilliseconds(FailTimeoutMilliseconds), true),
};
var t =
new Thread(() =>
{
Monitor.Enter(obj);
for (int i = 0; i < waitTests.Length; ++i)
{
Monitor.Pulse(obj);
Monitor.Wait(obj, FailTimeoutMilliseconds);
}
Monitor.Exit(obj);
});
t.IsBackground = true;
Monitor.Enter(obj);
t.Start();
foreach (var waitTest in waitTests)
{
Assert.True(waitTest());
Monitor.Pulse(obj);
}
Monitor.Exit(obj);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Enter_HasToWait_LockContentionCountTest()
{
long initialLockContentionCount = Monitor.LockContentionCount;
Enter_HasToWait();
Assert.True(Monitor.LockContentionCount - initialLockContentionCount >= 2);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ObjectHeaderSyncBlockTransitionTryEnterRaceTest()
{
var threadStarted = new AutoResetEvent(false);
var startTest = new AutoResetEvent(false);
var obj = new object();
var t = ThreadTestHelpers.CreateGuardedThread(out _, () =>
{
threadStarted.Set();
startTest.CheckedWait();
Monitor.TryEnter(obj, 100); // likely to perform a full wait, which may involve some sort of transition
});
t.IsBackground = true;
t.Start();
threadStarted.CheckedWait();
lock (obj)
{
startTest.Set();
do
{
for (int i = 0; i < 1000; i++)
{
Assert.True(Monitor.TryEnter(obj)); // this could race with the transition happening on the other thread
Monitor.Exit(obj);
}
} while (!t.Join(0));
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/49521", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[ActiveIssue("https://github.com/dotnet/runtimelab/issues/155", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))]
public static void InterruptWaitTest()
{
object obj = new();
lock (obj)
{
var threadReady = new AutoResetEvent(false);
var t =
ThreadTestHelpers.CreateGuardedThread(out Action waitForThread, () =>
{
threadReady.Set();
Assert.Throws<ThreadInterruptedException>(() => Monitor.Enter(obj));
});
t.IsBackground = true;
t.Start();
threadReady.CheckedWait();
t.Interrupt();
waitForThread();
}
}
}
}