-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadsFeaturesUnitDemos.cs
More file actions
315 lines (270 loc) · 8.28 KB
/
Copy pathThreadsFeaturesUnitDemos.cs
File metadata and controls
315 lines (270 loc) · 8.28 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
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Xunit;
namespace Neomaster.Demos.Tests.Threads;
[Description("Features")]
public class ThreadsFeaturesUnitDemos
{
[Fact(DisplayName = "Synchronized method: instance")]
public void SynchronizedMethod_Instance()
{
var obj = new SynchronizedMethodClass();
var chars = new ConcurrentQueue<char>();
const string expectedCharsString = "AAAAABBBBBCCCCCDDDDD";
for (char c = 'A'; c <= 'D'; c++)
{
obj.Count(chars, 5, c);
}
var charsString = string.Concat(chars);
Assert.Equal(expectedCharsString, charsString);
}
[Fact(DisplayName = "Synchronized method: static")]
public void SynchronizedMethod_Static()
{
var chars = new ConcurrentQueue<char>();
const string expectedCharsString = "AAAAABBBBBCCCCCDDDDD";
for (char c = 'A'; c <= 'D'; c++)
{
SynchronizedMethodClass.CountStatic(chars, 5, c);
}
var charsString = string.Concat(chars);
Assert.Equal(expectedCharsString, charsString);
}
[Fact(DisplayName = "Synchronized method: instance in different threads")]
public void SynchronizedMethod_InstanceInDifferentThreads()
{
var obj1 = new SynchronizedMethodClass();
var obj2 = new SynchronizedMethodClass();
var chars = new ConcurrentQueue<char>();
const string expectedChars1String = "AAAAABBBBBCCCCCDDDDD";
const string expectedChars2String = "11111222223333344444";
const int charNumber = 5;
var th1 = new Thread(() =>
{
for (char c = 'A'; c <= 'D'; c++)
{
obj1.Count(chars, charNumber, c);
}
});
var th2 = new Thread(() =>
{
for (char c = '1'; c <= '4'; c++)
{
obj2.Count(chars, charNumber, c);
}
});
th1.Start();
th2.Start();
th1.Join();
th2.Join();
var charsString = string.Concat(chars);
var uniqueChars = chars.Distinct();
// Demonstrates that the object being locked is "this".
foreach (var uc in uniqueChars)
{
var ucSeq = new string(uc, charNumber);
Assert.DoesNotContain(ucSeq, charsString);
}
var chars1String = string.Concat(chars.Where(c => c >= 'A'));
var chars2String = string.Concat(chars.Where(c => c < 'A'));
Assert.Equal(expectedChars1String, chars1String);
Assert.Equal(expectedChars2String, chars2String);
}
[Fact(DisplayName = "Synchronized method: static in different threads")]
public void SynchronizedMethod_StaticInDifferentThreads()
{
var chars = new ConcurrentQueue<char>();
const string expectedChars1String = "AAAAABBBBBCCCCCDDDDD";
const string expectedChars2String = "11111222223333344444";
const int charNumber = 5;
var th1 = new Thread(() =>
{
for (char c = 'A'; c <= 'D'; c++)
{
SynchronizedMethodClass.CountStatic(chars, charNumber, c);
}
});
var th2 = new Thread(() =>
{
for (char c = '1'; c <= '4'; c++)
{
SynchronizedMethodClass.CountStatic(chars, charNumber, c);
}
});
th1.Start();
th2.Start();
th1.Join();
th2.Join();
var charsString = string.Concat(chars);
var uniqueChars = chars.Distinct();
// Demonstrates that the object being locked is the instance of "typeof(SynchronizedMethodClass)".
foreach (var uc in uniqueChars)
{
var ucSeq = new string(uc, charNumber);
Assert.Contains(ucSeq, charsString);
}
var chars1String = string.Concat(chars.Where(c => c >= 'A'));
var chars2String = string.Concat(chars.Where(c => c < 'A'));
Assert.Equal(expectedChars1String, chars1String);
Assert.Equal(expectedChars2String, chars2String);
}
[Fact(DisplayName = "ThreadLocal<T>: counters")]
public void ThreadLocal_Counters()
{
var threadCounters = new int[3];
using (var threadLocalCounter = new ThreadLocal<int>(() => 0))
{
var threads = Enumerable.Range(1, 3)
.Select(n => new Thread(() =>
{
threadLocalCounter.Value = n;
threadCounters[n - 1] = threadLocalCounter.Value;
}))
.ToList();
threads.ForEach(th => th.Start());
threads.ForEach(th => th.Join());
}
Assert.Equal([1, 2, 3], threadCounters);
}
[Fact(DisplayName = "Lazy<T>: lazy initialization")]
public void LazyLazyInitialization()
{
var lo = new Lazy<bool>();
Assert.False(lo.IsValueCreated);
_ = lo.Value;
Assert.True(lo.IsValueCreated);
}
[Fact(DisplayName = "Lazy<T>: single initialization")]
public void LazySingleInitialization()
{
var initializedEventCount = 0;
var loValueAccessErrorCount = 0;
var lo = new Lazy<string>(
() =>
{
Interlocked.Increment(ref initializedEventCount);
return "1";
},
LazyThreadSafetyMode.ExecutionAndPublication); // isThreadSafe: true
var threads = Enumerable.Range(1, 20)
.Select(i => new Thread(() =>
{
try
{
_ = lo.Value;
}
catch (InvalidOperationException)
{
Interlocked.Increment(ref loValueAccessErrorCount);
}
}))
.ToList();
threads.ForEach(th => th.Start());
threads.ForEach(th => th.Join());
Assert.Equal(1, initializedEventCount);
Assert.Equal(0, loValueAccessErrorCount);
}
[Fact(DisplayName = "Lazy<T>: multiple initialization")]
public void LazyMultipleInitialization()
{
var initializedEventCount = 0;
var loValueAccessErrorCount = 0;
var initializationValues = new List<string>();
var returnValues = new List<string>();
var lo = new Lazy<string>(
() =>
{
Thread.Sleep(100);
Interlocked.Increment(ref initializedEventCount);
var value = DateTime.Now.ToString("mm:ss.fff");
initializationValues.Add(value);
return value;
},
LazyThreadSafetyMode.PublicationOnly);
var threads = Enumerable.Range(1, 20)
.Select(i => new Thread(() =>
{
try
{
returnValues.Add(lo.Value);
}
catch (InvalidOperationException)
{
Interlocked.Increment(ref loValueAccessErrorCount);
}
}))
.ToList();
threads.ForEach(th => th.Start());
threads.ForEach(th => th.Join());
Assert.True(initializedEventCount > 1);
Assert.True(initializationValues.Count > 1);
Assert.Equal(0, loValueAccessErrorCount);
Assert.Single(returnValues.Distinct());
}
[Fact(DisplayName = "Lazy<T>: unsafe initialization")]
public void LazyUnsafeInitialization()
{
var initializedEventCount = 0;
var loValueAccessErrorCount = 0;
var lo = new Lazy<string>(
() =>
{
Thread.Sleep(100);
Interlocked.Increment(ref initializedEventCount);
return "1";
},
LazyThreadSafetyMode.None); // isThreadSafe: false
var threads = Enumerable.Range(1, 20)
.Select(i => new Thread(() =>
{
try
{
_ = lo.Value;
}
catch (InvalidOperationException)
{
Interlocked.Increment(ref loValueAccessErrorCount);
}
}))
.ToList();
threads.ForEach(th => th.Start());
threads.ForEach(th => th.Join());
Assert.True(initializedEventCount >= 1);
Assert.True(loValueAccessErrorCount > 0);
}
[Fact(DisplayName = "Note: disposable sync primitives")]
public void NoteDisposableSyncPrimitives()
{
using var m = new Mutex();
using var s = new Semaphore(1, 1);
using var sl = new SemaphoreSlim(1, 1);
using var b = new Barrier(1);
using var ce = new CountdownEvent(1);
using var ewh = new EventWaitHandle(default, default);
using var are = new AutoResetEvent(default);
using var mre = new ManualResetEvent(default);
using var mres = new ManualResetEventSlim(default);
}
public class SynchronizedMethodClass
{
[MethodImpl(MethodImplOptions.Synchronized)]
public static void CountStatic(ConcurrentQueue<char> chars, int number, char c)
{
for (var i = 0; i < number; i++)
{
Thread.Sleep(50);
chars.Enqueue(c);
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Count(ConcurrentQueue<char> chars, int number, char c)
{
for (var i = 0; i < number; i++)
{
Thread.Sleep(50);
chars.Enqueue(c);
}
}
}
}