2 // System.Threading.ReaderWriterLock.cs
5 // Dick Porter (dick@ximian.com)
6 // Jackson Harper (jackson@ximian.com)
7 // Lluis Sanchez Gual (lluis@ximian.com)
9 // (C) Ximian, Inc. http://www.ximian.com
10 // (C) 2004 Novell, Inc (http://www.novell.com)
14 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
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.
36 using System.Collections;
37 using System.Runtime.InteropServices;
38 using System.Runtime.ConstrainedExecution;
41 namespace System.Threading
44 public sealed class ReaderWriterLock: CriticalFinalizerObject
46 private int seq_num = 1;
49 private int writer_lock_owner;
50 private LockQueue writer_queue;
51 private Hashtable reader_locks;
53 public ReaderWriterLock()
55 writer_queue = new LockQueue (this);
56 reader_locks = new Hashtable ();
58 GC.SuppressFinalize (this);
65 public bool IsReaderLockHeld {
66 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
68 lock (this) return reader_locks.ContainsKey (Thread.CurrentThreadId);
72 public bool IsWriterLockHeld {
73 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
75 lock (this) return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
79 public int WriterSeqNum {
81 lock (this) return seq_num;
85 public void AcquireReaderLock (int millisecondsTimeout)
87 AcquireReaderLock (millisecondsTimeout, 1);
90 void AcquireReaderLock (int millisecondsTimeout, int initialLockCount)
93 if (HasWriterLock ()) {
94 AcquireWriterLock (millisecondsTimeout, initialLockCount);
98 object nlocks = reader_locks [Thread.CurrentThreadId];
101 // Not currently holding a reader lock
102 // Wait if there is a write lock
105 if (state < 0 || !writer_queue.IsEmpty) {
107 if (!Monitor.Wait (this, millisecondsTimeout))
108 throw new ApplicationException ("Timeout expired");
116 reader_locks [Thread.CurrentThreadId] = initialLockCount;
117 state += initialLockCount;
120 reader_locks [Thread.CurrentThreadId] = ((int)nlocks) + 1;
126 public void AcquireReaderLock(TimeSpan timeout)
128 int ms = CheckTimeout (timeout);
129 AcquireReaderLock (ms, 1);
132 public void AcquireWriterLock (int millisecondsTimeout)
134 AcquireWriterLock (millisecondsTimeout, 1);
137 void AcquireWriterLock (int millisecondsTimeout, int initialLockCount)
140 if (HasWriterLock ()) {
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) {
149 if (!writer_queue.Wait (millisecondsTimeout))
150 throw new ApplicationException ("Timeout expired");
151 } while (state != 0);
154 state = -initialLockCount;
155 writer_lock_owner = Thread.CurrentThreadId;
160 public void AcquireWriterLock(TimeSpan timeout) {
161 int ms = CheckTimeout (timeout);
162 AcquireWriterLock (ms, 1);
165 public bool AnyWritersSince(int seqNum) {
167 return (this.seq_num > seqNum);
171 public void DowngradeFromWriterLock(ref LockCookie lockCookie)
174 if (!HasWriterLock())
175 throw new ApplicationException ("The thread does not have the writer lock.");
177 if (lockCookie.WriterLocks != 0)
180 state = lockCookie.ReaderLocks;
181 reader_locks [Thread.CurrentThreadId] = state;
183 Monitor.PulseAll (this);
187 // MSDN: A thread does not block when downgrading from the writer lock,
188 // even if other threads are waiting for the writer lock
192 public LockCookie ReleaseLock()
196 cookie = GetLockCookie ();
197 if (cookie.WriterLocks != 0)
198 ReleaseWriterLock (cookie.WriterLocks);
199 else if (cookie.ReaderLocks != 0) {
200 ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
206 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
207 public void ReleaseReaderLock()
210 if (HasWriterLock ()) {
211 ReleaseWriterLock ();
214 else if (state > 0) {
215 object read_lock_count = reader_locks [Thread.CurrentThreadId];
216 if (read_lock_count != null) {
217 ReleaseReaderLock ((int)read_lock_count, 1);
222 throw new ApplicationException ("The thread does not have any reader or writer locks.");
226 void ReleaseReaderLock (int currentCount, int releaseCount)
228 int new_count = currentCount - releaseCount;
231 reader_locks.Remove (Thread.CurrentThreadId);
233 reader_locks [Thread.CurrentThreadId] = new_count;
235 state -= releaseCount;
236 if (state == 0 && !writer_queue.IsEmpty)
237 writer_queue.Pulse ();
240 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
241 public void ReleaseWriterLock()
244 if (!HasWriterLock())
245 throw new ApplicationException ("The thread does not have the writer lock.");
247 ReleaseWriterLock (1);
251 void ReleaseWriterLock (int releaseCount)
253 state += releaseCount;
256 Monitor.PulseAll (this);
258 else if (!writer_queue.IsEmpty)
259 writer_queue.Pulse ();
263 public void RestoreLock(ref LockCookie lockCookie)
266 if (lockCookie.WriterLocks != 0)
267 AcquireWriterLock (-1, lockCookie.WriterLocks);
268 else if (lockCookie.ReaderLocks != 0)
269 AcquireReaderLock (-1, lockCookie.ReaderLocks);
273 public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
277 cookie = GetLockCookie ();
278 if (cookie.WriterLocks != 0) {
283 if (cookie.ReaderLocks != 0)
284 ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
287 // Don't do this inside the lock, since it can cause a deadlock.
288 AcquireWriterLock (millisecondsTimeout);
292 public LockCookie UpgradeToWriterLock(TimeSpan timeout)
294 int ms = CheckTimeout (timeout);
295 return UpgradeToWriterLock (ms);
298 LockCookie GetLockCookie ()
300 LockCookie cookie = new LockCookie (Thread.CurrentThreadId);
303 cookie.WriterLocks = -state;
305 object locks = reader_locks [Thread.CurrentThreadId];
306 if (locks != null) cookie.ReaderLocks = (int)locks;
311 bool HasWriterLock ()
313 return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
316 private int CheckTimeout (TimeSpan timeout)
318 int ms = (int) timeout.TotalMilliseconds;
321 throw new ArgumentOutOfRangeException ("timeout",
322 "Number must be either non-negative or -1");