-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLockingDontWait.cs
81 lines (64 loc) · 1.92 KB
/
LockingDontWait.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
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BenchmarkLocks
{
[SimpleJob]
[DisassemblyDiagnoser(printSource: true)]
[ThreadingDiagnoser]
public class LockingDontWait
{
private double value = 0;
object mutex = new object();
[Benchmark(Baseline = true)]
public void NoLock()
{
unchecked { value += 1; }
}
[Benchmark]
public double UseLock()
{
bool lockTaken = false;
try
{
lockTaken = Monitor.TryEnter(mutex);
if (lockTaken)
{
unchecked { value += 1; }
}
}
catch (Exception)
{
throw;
}
finally
{
if (lockTaken)
Monitor.Exit(mutex);
}
return value;
}
private const int LOCKED = 1;
private const int UNLOCKED = 0;
private int atomicMutex = 0;
[Benchmark]
public double UseInterLockSpin()
{
if (System.Threading.Interlocked.CompareExchange(ref atomicMutex, LOCKED, UNLOCKED) == UNLOCKED)
{
// CompareExchange returned "UNLOCKED" as the original value, which means the value is NOW locked, since the
// operation is atomic, hence we took the lock.
// check https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked.compareexchange?view=net-8.0
unchecked { value += 1; }
// unlock after work:
System.Threading.Interlocked.Exchange(ref atomicMutex, UNLOCKED);
}
return value;
}
}
}