Repository navigation
Expand file tree
/
Copy pathThreadsAtomicOperationsUnitDemos.cs
More file actions
105 lines (84 loc) · 2.13 KB
/
Copy pathThreadsAtomicOperationsUnitDemos.cs
File metadata and controls
105 lines (84 loc) · 2.13 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
using System.ComponentModel;
using Xunit;
namespace Neomaster.Demos.Tests.Threads;
[Description("Atomic Operations")]
public class ThreadsAtomicOperationsUnitDemos
{
private static volatile bool _noncachedReady;
[Fact(DisplayName = "Volatile class")]
public void VolatileClass()
{
var ready = false;
int? data = null;
void Producer()
{
Thread.Sleep(100);
data = 1;
Volatile.Write(ref ready, true);
}
void Consumer()
{
while (!Volatile.Read(ref ready))
{
// The Consumer thread may get stuck in a while (!ready) loop
// because the processor may cache ready and not see it change.
}
}
var producerTh = new Thread(Producer);
var consumerTh = new Thread(Consumer);
producerTh.Start();
consumerTh.Start();
consumerTh.Join();
producerTh.Join();
Assert.Equal(1, data);
}
[Fact(DisplayName = "Volatile keyword")]
public void VolatileKeyword()
{
int? data = null;
void Producer()
{
Thread.Sleep(100);
data = 1;
_noncachedReady = true;
}
void Consumer()
{
while (!_noncachedReady)
{
// The Consumer thread may get stuck in a while (!ready) loop
// because the processor may cache ready and not see it change.
}
}
var producerTh = new Thread(Producer);
var consumerTh = new Thread(Consumer);
producerTh.Start();
consumerTh.Start();
consumerTh.Join();
producerTh.Join();
Assert.Equal(1, data);
}
[Fact(DisplayName = "Interlocked Increment")]
public void InterlockedIncrement()
{
const int threadNumber = 20;
const int threadSignalNumber = 100_000;
var sum1 = 0;
var sum2 = 0;
var threads = Enumerable
.Range(1, threadNumber)
.Select(_ => new Thread(() =>
{
for (var i = 0; i < threadSignalNumber; i++)
{
sum1++;
Interlocked.Increment(ref sum2);
}
}))
.ToList();
threads.ForEach(th => th.Start());
threads.ForEach(th => th.Join());
Assert.True(sum1 < sum2);
Assert.Equal(threadNumber * threadSignalNumber, sum2);
}
}