Merge pull request #1322 from StephenMcConnel/bug23532
[mono.git] / mcs / class / corlib / System.Threading / SemaphoreSlim.cs
1 // SemaphoreSlim.cs
2 //
3 // Copyright (c) 2008 Jérémie "Garuma" Laval
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 // THE SOFTWARE.
22 //
23 //
24
25 using System;
26 using System.Diagnostics;
27 #if NET_4_5
28 using System.Threading.Tasks;
29 #endif
30
31 #if NET_4_0
32 namespace System.Threading
33 {
34         [System.Diagnostics.DebuggerDisplayAttribute ("Current Count = {currCount}")]
35         public class SemaphoreSlim : IDisposable
36         {
37                 const int spinCount = 10;
38                 const int deepSleepTime = 20;
39
40                 readonly int maxCount;
41                 int currCount;
42                 bool isDisposed;
43
44                 EventWaitHandle handle;
45
46                 public SemaphoreSlim (int initialCount) : this (initialCount, int.MaxValue)
47                 {
48                 }
49
50                 public SemaphoreSlim (int initialCount, int maxCount)
51                 {
52                         if (initialCount < 0 || initialCount > maxCount || maxCount < 0)
53                                 throw new ArgumentOutOfRangeException ("The initialCount  argument is negative, initialCount is greater than maxCount, or maxCount is not positive.");
54
55                         this.maxCount = maxCount;
56                         this.currCount = initialCount;
57                         this.handle = new ManualResetEvent (initialCount > 0);
58                 }
59
60                 public void Dispose ()
61                 {
62                         Dispose(true);
63                 }
64
65                 protected virtual void Dispose (bool disposing)
66                 {
67                         isDisposed = true;
68                 }
69
70                 void CheckState ()
71                 {
72                         if (isDisposed)
73                                 throw new ObjectDisposedException ("The SemaphoreSlim has been disposed.");
74                 }
75
76                 public int CurrentCount {
77                         get {
78                                 return currCount;
79                         }
80                 }
81
82                 public int Release ()
83                 {
84                         return Release(1);
85                 }
86
87                 public int Release (int releaseCount)
88                 {
89                         CheckState ();
90                         if (releaseCount < 1)
91                                 throw new ArgumentOutOfRangeException ("releaseCount", "releaseCount is less than 1");
92
93                         // As we have to take care of the max limit we resort to CAS
94                         int oldValue, newValue;
95                         do {
96                                 oldValue = currCount;
97                                 newValue = (currCount + releaseCount);
98                                 newValue = newValue > maxCount ? maxCount : newValue;
99                         } while (Interlocked.CompareExchange (ref currCount, newValue, oldValue) != oldValue);
100
101                         handle.Set ();
102
103                         return oldValue;
104                 }
105
106                 public void Wait ()
107                 {
108                         Wait (CancellationToken.None);
109                 }
110
111                 public bool Wait (TimeSpan timeout)
112                 {
113                         return Wait ((int)timeout.TotalMilliseconds, CancellationToken.None);
114                 }
115
116                 public bool Wait (int millisecondsTimeout)
117                 {
118                         return Wait (millisecondsTimeout, CancellationToken.None);
119                 }
120
121                 public void Wait (CancellationToken cancellationToken)
122                 {
123                         Wait (-1, cancellationToken);
124                 }
125
126                 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
127                 {
128                         CheckState();
129                         return Wait ((int)timeout.TotalMilliseconds, cancellationToken);
130                 }
131
132                 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
133                 {
134                         CheckState ();
135                         if (millisecondsTimeout < -1)
136                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout",
137                                                                        "millisecondsTimeout is a negative number other than -1");
138
139                         Watch sw = Watch.StartNew ();
140
141                         Func<bool> stopCondition = () => millisecondsTimeout >= 0 && sw.ElapsedMilliseconds > millisecondsTimeout;
142
143                         do {
144                                 bool shouldWait;
145                                 int result;
146
147                                 do {
148                                         cancellationToken.ThrowIfCancellationRequested ();
149                                         if (stopCondition ())
150                                                 return false;
151
152                                         shouldWait = true;
153                                         result = currCount;
154
155                                         if (result > 0)
156                                                 shouldWait = false;
157                                         else
158                                                 break;
159                                 } while (Interlocked.CompareExchange (ref currCount, result - 1, result) != result);
160
161                                 if (!shouldWait) {
162                                         if (result == 1)
163                                                 handle.Reset ();
164                                         break;
165                                 }
166
167                                 SpinWait wait = new SpinWait ();
168
169                                 while (Volatile.Read (ref currCount) <= 0) {
170                                         cancellationToken.ThrowIfCancellationRequested ();
171                                         if (stopCondition ())
172                                                 return false;
173
174                                         if (wait.Count > spinCount) {
175                                                 int timeout = millisecondsTimeout < 0 ? deepSleepTime :
176                                                         Math.Min (Math.Max (millisecondsTimeout - (int)sw.ElapsedMilliseconds, 1), deepSleepTime);
177                                                 handle.WaitOne (timeout);
178                                         } else
179                                                 wait.SpinOnce ();
180                                 }
181                         } while (true);
182
183                         return true;
184                 }
185
186                 public WaitHandle AvailableWaitHandle {
187                         get {
188                                 return handle;
189                         }
190                 }
191
192 #if NET_4_5
193                 public Task WaitAsync ()
194                 {
195                         return Task.Factory.StartNew (() => Wait ());
196                 }
197
198                 public Task WaitAsync (CancellationToken cancellationToken)
199                 {
200                         return Task.Factory.StartNew (() => Wait (cancellationToken), cancellationToken);
201                 }
202
203                 public Task<bool> WaitAsync (int millisecondsTimeout)
204                 {
205                         return Task.Factory.StartNew (() => Wait (millisecondsTimeout));
206                 }
207
208                 public Task<bool> WaitAsync (TimeSpan timeout)
209                 {
210                         return Task.Factory.StartNew (() => Wait (timeout));
211                 }
212
213                 public Task<bool> WaitAsync (int millisecondsTimeout, CancellationToken cancellationToken)
214                 {
215                         return Task.Factory.StartNew (() => Wait (millisecondsTimeout, cancellationToken), cancellationToken);
216                 }
217
218                 public Task<bool> WaitAsync (TimeSpan timeout, CancellationToken cancellationToken)
219                 {
220                         return Task.Factory.StartNew (() => Wait (timeout, cancellationToken), cancellationToken);
221                 }
222 #endif
223
224         }
225 }
226 #endif