2010-06-07 Jonathan Chambers <joncham@gmail.com>
[mono.git] / mcs / class / corlib / System.Threading / ReaderWriterLock.cs
1 //
2 // System.Threading.ReaderWriterLock.cs
3 //
4 // Author:
5 //   Dick Porter (dick@ximian.com)
6 //   Jackson Harper (jackson@ximian.com)
7 //   Lluis Sanchez Gual (lluis@ximian.com)
8 //
9 // (C) Ximian, Inc.  http://www.ximian.com
10 // (C) 2004 Novell, Inc (http://www.novell.com)
11 //
12
13 //
14 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
15 //
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
23 // 
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
26 // 
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 //
35
36 using System.Collections;
37 using System.Runtime.InteropServices;
38 using System.Runtime.ConstrainedExecution;
39
40
41 namespace System.Threading
42 {
43         [ComVisible (true)]
44         public sealed class ReaderWriterLock: CriticalFinalizerObject
45         {
46                 private int seq_num = 1;
47                 private int state;
48                 private int readers;
49                 private LockQueue writer_queue;
50                 private Hashtable reader_locks;
51                 private int writer_lock_owner;
52
53                 public ReaderWriterLock()
54                 {
55                         writer_queue = new LockQueue (this);
56                         reader_locks = new Hashtable ();
57
58                         GC.SuppressFinalize (this);
59                 }
60
61                 ~ReaderWriterLock ()
62                 {
63                 }
64
65                 public bool IsReaderLockHeld {
66                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
67                         get {
68                                 lock (this) return reader_locks.ContainsKey (Thread.CurrentThreadId);
69                         }
70                 }
71
72                 public bool IsWriterLockHeld {
73                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
74                         get {
75                                 lock (this) return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
76                         }
77                 }
78
79                 public int WriterSeqNum {
80                         get {
81                                 lock (this) return seq_num;
82                         }
83                 }
84
85                 public void AcquireReaderLock (int millisecondsTimeout) 
86                 {
87                         AcquireReaderLock (millisecondsTimeout, 1);
88                 }
89                 
90                 void AcquireReaderLock (int millisecondsTimeout, int initialLockCount) 
91                 {
92                         lock (this) {
93                                 if (HasWriterLock ()) {
94                                         AcquireWriterLock (millisecondsTimeout, initialLockCount);
95                                         return;
96                                 }
97                                 
98                                 object nlocks = reader_locks [Thread.CurrentThreadId];
99                                 if (nlocks == null)
100                                 {
101                                         // Not currently holding a reader lock
102                                         // Wait if there is a write lock
103                                         readers++;
104                                         try {
105                                                 if (state < 0 || !writer_queue.IsEmpty) {
106                                                         do {
107                                                                 if (!Monitor.Wait (this, millisecondsTimeout))
108                                                                         throw new ApplicationException ("Timeout expired");
109                                                         } while (state < 0);
110                                                 }
111                                         }
112                                         finally {
113                                                 readers--;
114                                         }
115                                         
116                                         reader_locks [Thread.CurrentThreadId] = initialLockCount;
117                                         state += initialLockCount;
118                                 }
119                                 else {
120                                         reader_locks [Thread.CurrentThreadId] = ((int)nlocks) + 1;
121                                         state++;
122                                 }
123                         }
124                 }
125
126                 public void AcquireReaderLock(TimeSpan timeout)
127                 {
128                         int ms = CheckTimeout (timeout);
129                         AcquireReaderLock (ms, 1);
130                 }
131
132                 public void AcquireWriterLock (int millisecondsTimeout)
133                 {
134                         AcquireWriterLock (millisecondsTimeout, 1);
135                 }
136                 
137                 void AcquireWriterLock (int millisecondsTimeout, int initialLockCount)
138                 {
139                         lock (this) {
140                                 if (HasWriterLock ()) {
141                                         state--;
142                                         return;
143                                 }
144                                 
145                                 // wait while there are reader locks or another writer lock, or
146                                 // other threads waiting for the writer lock
147                                 if (state != 0 || !writer_queue.IsEmpty) {
148                                         do {
149                                                 if (!writer_queue.Wait (millisecondsTimeout))
150                                                         throw new ApplicationException ("Timeout expired");
151                                         } while (state != 0);
152                                 }
153
154                                 state = -initialLockCount;
155                                 writer_lock_owner = Thread.CurrentThreadId;
156                                 seq_num++;
157                         }
158                 }
159
160                 public void AcquireWriterLock(TimeSpan timeout) {
161                         int ms = CheckTimeout (timeout);
162                         AcquireWriterLock (ms, 1);
163                 }
164
165                 public bool AnyWritersSince(int seqNum) {
166                         lock (this) {
167                                 return (this.seq_num > seqNum);
168                         }
169                 }
170
171                 public void DowngradeFromWriterLock(ref LockCookie lockCookie)
172                 {
173                         lock (this) {
174                                 if (!HasWriterLock())
175                                         throw new ApplicationException ("The thread does not have the writer lock.");
176                                 
177                                 state = lockCookie.ReaderLocks;
178                                 reader_locks [Thread.CurrentThreadId] = state;
179                                 if (readers > 0) {
180                                         Monitor.PulseAll (this);
181                                 }
182                                 
183                                 // MSDN: A thread does not block when downgrading from the writer lock, 
184                                 // even if other threads are waiting for the writer lock
185                         }
186                 }
187
188                 public LockCookie ReleaseLock()
189                 {
190                         LockCookie cookie;
191                         lock (this) {
192                                 cookie = GetLockCookie ();
193                                 if (cookie.WriterLocks != 0)
194                                         ReleaseWriterLock (cookie.WriterLocks);
195                                 else if (cookie.ReaderLocks != 0) {
196                                         ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
197                                 }
198                         }
199                         return cookie;
200                 }
201                 
202                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
203                 public void ReleaseReaderLock()
204                 {
205                         lock (this) {
206                                 if (HasWriterLock ()) {
207                                         ReleaseWriterLock ();
208                                         return;
209                                 }
210                                 else if (state > 0) {
211                                         object read_lock_count = reader_locks [Thread.CurrentThreadId];
212                                         if (read_lock_count != null) {
213                                                 ReleaseReaderLock ((int)read_lock_count, 1);
214                                                 return;
215                                         }
216                                 }
217
218                                 throw new ApplicationException ("The thread does not have any reader or writer locks.");
219                         }
220                 }
221
222                 void ReleaseReaderLock (int currentCount, int releaseCount)
223                 {
224                         int new_count = currentCount - releaseCount;
225                         
226                         if (new_count == 0)
227                                 reader_locks.Remove (Thread.CurrentThreadId);
228                         else
229                                 reader_locks [Thread.CurrentThreadId] = new_count;
230                                 
231                         state -= releaseCount;
232                         if (state == 0 && !writer_queue.IsEmpty)
233                                 writer_queue.Pulse ();
234                 }
235
236                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
237                 public void ReleaseWriterLock()
238                 {
239                         lock (this) {
240                                 if (!HasWriterLock())
241                                         throw new ApplicationException ("The thread does not have the writer lock.");
242                                 
243                                 ReleaseWriterLock (1);
244                         }
245                 }
246
247                 void ReleaseWriterLock (int releaseCount)
248                 {
249                         state += releaseCount;
250                         if (state == 0) {
251                                 if (readers > 0) {
252                                         Monitor.PulseAll (this);
253                                 }
254                                 else if (!writer_queue.IsEmpty)
255                                         writer_queue.Pulse ();
256                         }
257                 }
258                 
259                 public void RestoreLock(ref LockCookie lockCookie)
260                 {
261                         lock (this) {
262                                 if (lockCookie.WriterLocks != 0)
263                                         AcquireWriterLock (-1, lockCookie.WriterLocks);
264                                 else if (lockCookie.ReaderLocks != 0)
265                                         AcquireReaderLock (-1, lockCookie.ReaderLocks);
266                         }
267                 }
268
269                 public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
270                 {
271                         LockCookie cookie;
272                         lock (this) {
273                                 cookie = GetLockCookie ();
274                                 if (cookie.WriterLocks != 0) {
275                                         state--;
276                                         return cookie;
277                                 }
278                                 
279                                 if (cookie.ReaderLocks != 0)
280                                         ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
281                         }
282                         
283                         // Don't do this inside the lock, since it can cause a deadlock.
284                         AcquireWriterLock (millisecondsTimeout);
285                         return cookie;
286                 }
287                 
288                 public LockCookie UpgradeToWriterLock(TimeSpan timeout)
289                 {
290                         int ms = CheckTimeout (timeout);
291                         return UpgradeToWriterLock (ms);
292                 }
293                 
294                 LockCookie GetLockCookie ()
295                 {
296                         LockCookie cookie = new LockCookie (Thread.CurrentThreadId);
297                         
298                         if (HasWriterLock())
299                                 cookie.WriterLocks = -state;
300                         else {
301                                 object locks = reader_locks [Thread.CurrentThreadId];
302                                 if (locks != null) cookie.ReaderLocks = (int)locks;
303                         }
304                         return cookie;
305                 }
306
307                 bool HasWriterLock ()
308                 {
309                         return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
310                 }
311                 
312                 private int CheckTimeout (TimeSpan timeout)
313                 {
314                         int ms = (int) timeout.TotalMilliseconds;
315
316                         if (ms < -1)
317                                 throw new ArgumentOutOfRangeException ("timeout",
318                                                 "Number must be either non-negative or -1");
319                         return ms;
320                 }
321         }
322 }
323