From 0266ad9d591b3c7c27c44c7f7430107161671cd8 Mon Sep 17 00:00:00 2001 From: noisyfox Date: Sat, 27 Aug 2016 17:24:42 +1000 Subject: [PATCH] Remove redundant lock. Lock is evil. This will actually affect the accuracy of GetDelta because inboundDelta and outboundDelta may be calculated based on the data collected at different time (eg. UpdateOutbound get called before Interlocked.Read(ref _outbound)). But that's not a problem. We can tolerate this little inaccuracy. Besides, the _inbound, _outbound, _lastInbound and _lastOutbound will be totally good because we use Interlocked. --- .../Service/AvailabilityStatistics.cs | 56 +++---------------- 1 file changed, 9 insertions(+), 47 deletions(-) diff --git a/shadowsocks-csharp/Controller/Service/AvailabilityStatistics.cs b/shadowsocks-csharp/Controller/Service/AvailabilityStatistics.cs index a691d0e8..6ce5eb45 100644 --- a/shadowsocks-csharp/Controller/Service/AvailabilityStatistics.cs +++ b/shadowsocks-csharp/Controller/Service/AvailabilityStatistics.cs @@ -37,6 +37,7 @@ namespace Shadowsocks.Controller private readonly ConcurrentDictionary> _inboundSpeedRecords = new ConcurrentDictionary>(); private readonly ConcurrentDictionary> _outboundSpeedRecords = new ConcurrentDictionary>(); private readonly ConcurrentDictionary _inOutBoundRecords = new ConcurrentDictionary(); + private class InOutBoundRecord { private long _inbound; @@ -44,65 +45,26 @@ namespace Shadowsocks.Controller private long _outbound; private long _lastOutbound; - private SpinLock _lock = new SpinLock(); - public void UpdateInbound(long delta) { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - Interlocked.Add(ref _inbound, delta); - } - finally - { - if (lockTaken) - { - _lock.Exit(false); - } - } + Interlocked.Add(ref _inbound, delta); } public void UpdateOutbound(long delta) { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - Interlocked.Add(ref _outbound, delta); - } - finally - { - if (lockTaken) - { - _lock.Exit(false); - } - } + Interlocked.Add(ref _outbound, delta); } public void GetDelta(out long inboundDelta, out long outboundDelta) { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); + var i = Interlocked.Read(ref _inbound); + var il = Interlocked.Exchange(ref _lastInbound, i); + inboundDelta = i - il; - var i = Interlocked.Read(ref _inbound); - var il = Interlocked.Exchange(ref _lastInbound, i); - inboundDelta = i - il; - - var o = Interlocked.Read(ref _outbound); - var ol = Interlocked.Exchange(ref _lastOutbound, o); - outboundDelta = o - ol; - } - finally - { - if (lockTaken) - { - _lock.Exit(false); - } - } + var o = Interlocked.Read(ref _outbound); + var ol = Interlocked.Exchange(ref _lastOutbound, o); + outboundDelta = o - ol; } }