/
Program.cs
123 lines (113 loc) · 2.76 KB
/
Program.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
using System;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
class Program
{
public static void Main()
{
new BenchmarkLock().Run();
}
}
class BenchmarkLock
{
const int concurrency = 10;
const int count = 1000 * 1000;
int index;
public void Run()
{
ThreadPool.SetMinThreads(concurrency, concurrency);
ThreadPool.SetMaxThreads(concurrency, concurrency);
Console.WriteLine(string.Format("concurrency {0:n0}", concurrency));
Console.WriteLine(string.Format("count {0:n0}", count));
bench("unsafe ", broken);
bench("interlocked ", interlocked);
bench("lock ", lock_);
bench("semaphoreSlim ", semaphoreSlim);
bench("semaphore ", semaphore);
bench("mutex ", mutex);
}
void bench(string name, Action<int[]> f)
{
var s = Stopwatch.StartNew();
index = -1;
var length = count * concurrency;
var xs = new int[length];
var tasks = Enumerable.Range(1, concurrency).Select(async _ => {
await Task.Delay(1).ConfigureAwait(false);
for(int i=0; i<count; ++i)
{
f(xs);
}
}).ToArray();
Task.WaitAll(tasks);
Console.WriteLine("{0}: {1:n0} / sec ({2:n0} msec) | {3} {4}",
name,
(count * 1000) / s.ElapsedMilliseconds,
s.ElapsedMilliseconds,
xs.All(x => x == 1),
length == (1 + index));
}
void broken(int[] xs)
{
var n = ++index;
xs[n]++;
}
void interlocked(int[] xs)
{
var n = Interlocked.Increment(ref index);
xs[n]++;
}
object lockObject = new object();
void lock_(int[] xs)
{
lock(lockObject)
{
var n = ++index;
xs[n]++;
}
}
Semaphore sem = new Semaphore(1, 1);
void semaphore(int[] xs)
{
sem.WaitOne();
try
{
var n = ++index;
xs[n]++;
}
finally
{
sem.Release();
}
}
SemaphoreSlim semSlim = new SemaphoreSlim(1, 1);
void semaphoreSlim(int[] xs)
{
semSlim.Wait();
try
{
var n = ++index;
xs[n]++;
}
finally
{
semSlim.Release();
}
}
Mutex mut = new Mutex();
void mutex(int[] xs)
{
mut.WaitOne();
try
{
var n = ++index;
xs[n]++;
}
finally
{
mut.ReleaseMutex();
}
}
}