-
Notifications
You must be signed in to change notification settings - Fork 0
/
Monitors.dib
53 lines (40 loc) · 978 Bytes
/
Monitors.dib
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
#!markdown
# Common Resource - No Locks
#!csharp
const int NUMBER_OF_ITERATIONS = 32;
int globalSum = 0;
double result = 0d;
Task[] tasks = new Task[NUMBER_OF_ITERATIONS];
for (int i = 0; i < NUMBER_OF_ITERATIONS; i++)
{
tasks[i] = Task.Run(() =>
{
int cur = globalSum;
Task.Delay(NUMBER_OF_ITERATIONS - i /2 + 1);
globalSum = cur + 1;
});
}
Task.WaitAll(tasks);
Console.WriteLine(globalSum);
#!markdown
# Common Resource - With Locks
#!csharp
const int NUMBER_OF_ITERATIONS = 32;
int globalSum = 0;
object forGlobalLock = new object();
double result = 0d;
Task[] tasks = new Task[NUMBER_OF_ITERATIONS];
for (int i = 0; i < NUMBER_OF_ITERATIONS; i++)
{
tasks[i] = Task.Run(() =>
{
lock (forGlobalLock)
{
int cur = globalSum;
Task.Delay(NUMBER_OF_ITERATIONS - i /2 + 1);
globalSum = cur + 1;
}
});
}
Task.WaitAll(tasks);
Console.WriteLine(globalSum);