Update copyrights
[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
28 #if NET_4_0 || MOBILE
29 namespace System.Threading
30 {
31         [System.Diagnostics.DebuggerDisplayAttribute ("Current Count = {currCount}")]
32         public class SemaphoreSlim : IDisposable
33         {
34                 const int spinCount = 10;
35                 const int deepSleepTime = 20;
36
37                 readonly int maxCount;
38                 int currCount;
39                 bool isDisposed;
40
41                 EventWaitHandle handle;
42
43                 public SemaphoreSlim (int initialCount) : this (initialCount, int.MaxValue)
44                 {
45                 }
46
47                 public SemaphoreSlim (int initialCount, int maxCount)
48                 {
49                         if (initialCount < 0 || initialCount > maxCount || maxCount < 0)
50                                 throw new ArgumentOutOfRangeException ("The initialCount  argument is negative, initialCount is greater than maxCount, or maxCount is not positive.");
51
52                         this.maxCount = maxCount;
53                         this.currCount = initialCount;
54                         this.handle = new ManualResetEvent (initialCount == 0);
55                 }
56
57                 ~SemaphoreSlim ()
58                 {
59                         Dispose(false);
60                 }
61
62                 public void Dispose ()
63                 {
64                         Dispose(true);
65                 }
66
67                 protected virtual void Dispose (bool disposing)
68                 {
69                         isDisposed = true;
70                 }
71
72                 void CheckState ()
73                 {
74                         if (isDisposed)
75                                 throw new ObjectDisposedException ("The SemaphoreSlim has been disposed.");
76                 }
77
78                 public int CurrentCount {
79                         get {
80                                 return currCount;
81                         }
82                 }
83
84                 public int Release ()
85                 {
86                         return Release(1);
87                 }
88
89                 public int Release (int releaseCount)
90                 {
91                         CheckState ();
92                         if (releaseCount < 1)
93                                 throw new ArgumentOutOfRangeException ("releaseCount", "releaseCount is less than 1");
94
95                         // As we have to take care of the max limit we resort to CAS
96                         int oldValue, newValue;
97                         do {
98                                 oldValue = currCount;
99                                 newValue = (currCount + releaseCount);
100                                 newValue = newValue > maxCount ? maxCount : newValue;
101                         } while (Interlocked.CompareExchange (ref currCount, newValue, oldValue) != oldValue);
102
103                         handle.Set ();
104
105                         return oldValue;
106                 }
107
108                 public void Wait ()
109                 {
110                         Wait (CancellationToken.None);
111                 }
112
113                 public bool Wait (TimeSpan timeout)
114                 {
115                         return Wait ((int)timeout.TotalMilliseconds, CancellationToken.None);
116                 }
117
118                 public bool Wait (int millisecondsTimeout)
119                 {
120                         return Wait (millisecondsTimeout, CancellationToken.None);
121                 }
122
123                 public void Wait (CancellationToken cancellationToken)
124                 {
125                         Wait (-1, cancellationToken);
126                 }
127
128                 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
129                 {
130                         CheckState();
131                         return Wait ((int)timeout.TotalMilliseconds, cancellationToken);
132                 }
133
134                 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
135                 {
136                         CheckState ();
137                         if (millisecondsTimeout < -1)
138                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout",
139                                                                        "millisecondsTimeout is a negative number other than -1");
140
141                         Watch sw = Watch.StartNew ();
142
143                         Func<bool> stopCondition = () => millisecondsTimeout >= 0 && sw.ElapsedMilliseconds > millisecondsTimeout;
144
145                         do {
146                                 bool shouldWait;
147                                 int result;
148
149                                 do {
150                                         cancellationToken.ThrowIfCancellationRequested ();
151                                         if (stopCondition ())
152                                                 return false;
153
154                                         shouldWait = true;
155                                         result = currCount;
156
157                                         if (result > 0)
158                                                 shouldWait = false;
159                                         else
160                                                 break;
161                                 } while (Interlocked.CompareExchange (ref currCount, result - 1, result) != result);
162
163                                 if (!shouldWait) {
164                                         if (result == 1)
165                                                 handle.Reset ();
166                                         break;
167                                 }
168
169                                 SpinWait wait = new SpinWait ();
170
171                                 while (Thread.VolatileRead (ref currCount) <= 0) {
172                                         cancellationToken.ThrowIfCancellationRequested ();
173                                         if (stopCondition ())
174                                                 return false;
175
176                                         if (wait.Count > spinCount)
177                                                 handle.WaitOne (Math.Min (Math.Max (millisecondsTimeout - (int)sw.ElapsedMilliseconds, 1), deepSleepTime));
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 }
193 #endif