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;
39 using System.Runtime.InteropServices;
40 using System.Runtime.ConstrainedExecution;
43 namespace System.Threading
47 public sealed class ReaderWriterLock: CriticalFinalizerObject
49 public sealed class ReaderWriterLock
52 private int seq_num = 1;
55 private LockQueue writer_queue;
56 private Hashtable reader_locks;
57 private int writer_lock_owner;
59 public ReaderWriterLock()
61 writer_queue = new LockQueue (this);
62 reader_locks = new Hashtable ();
65 GC.SuppressFinalize (this);
76 public bool IsReaderLockHeld {
78 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
81 lock (this) return reader_locks.ContainsKey (Thread.CurrentThreadId);
85 public bool IsWriterLockHeld {
87 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
90 lock (this) return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
94 public int WriterSeqNum {
96 lock (this) return seq_num;
100 public void AcquireReaderLock (int millisecondsTimeout)
102 AcquireReaderLock (millisecondsTimeout, 1);
105 void AcquireReaderLock (int millisecondsTimeout, int initialLockCount)
108 if (HasWriterLock ()) {
109 AcquireWriterLock (millisecondsTimeout, initialLockCount);
113 object nlocks = reader_locks [Thread.CurrentThreadId];
116 // Not currently holding a reader lock
117 // Wait if there is a write lock
120 if (state < 0 || !writer_queue.IsEmpty) {
122 if (!Monitor.Wait (this, millisecondsTimeout))
123 throw new ApplicationException ("Timeout expired");
131 reader_locks [Thread.CurrentThreadId] = initialLockCount;
132 state += initialLockCount;
135 reader_locks [Thread.CurrentThreadId] = ((int)nlocks) + 1;
141 public void AcquireReaderLock(TimeSpan timeout)
143 int ms = CheckTimeout (timeout);
144 AcquireReaderLock (ms, 1);
147 public void AcquireWriterLock (int millisecondsTimeout)
149 AcquireWriterLock (millisecondsTimeout, 1);
152 void AcquireWriterLock (int millisecondsTimeout, int initialLockCount)
155 if (HasWriterLock ()) {
160 // wait while there are reader locks or another writer lock, or
161 // other threads waiting for the writer lock
162 if (state != 0 || !writer_queue.IsEmpty) {
164 if (!writer_queue.Wait (millisecondsTimeout))
165 throw new ApplicationException ("Timeout expired");
166 } while (state != 0);
169 state = -initialLockCount;
170 writer_lock_owner = Thread.CurrentThreadId;
175 public void AcquireWriterLock(TimeSpan timeout) {
176 int ms = CheckTimeout (timeout);
177 AcquireWriterLock (ms, 1);
180 public bool AnyWritersSince(int seqNum) {
182 return (this.seq_num > seqNum);
186 public void DowngradeFromWriterLock(ref LockCookie lockCookie)
189 if (!HasWriterLock())
190 throw new ApplicationException ("The thread does not have the writer lock.");
192 state = lockCookie.ReaderLocks;
193 reader_locks [Thread.CurrentThreadId] = state;
195 Monitor.PulseAll (this);
198 // MSDN: A thread does not block when downgrading from the writer lock,
199 // even if other threads are waiting for the writer lock
203 public LockCookie ReleaseLock()
207 cookie = GetLockCookie ();
208 if (cookie.WriterLocks != 0)
209 ReleaseWriterLock (cookie.WriterLocks);
210 else if (cookie.ReaderLocks != 0) {
211 ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
218 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
220 public void ReleaseReaderLock()
223 if (HasWriterLock ()) {
224 ReleaseWriterLock ();
227 else if (state > 0) {
228 object read_lock_count = reader_locks [Thread.CurrentThreadId];
229 if (read_lock_count != null) {
230 ReleaseReaderLock ((int)read_lock_count, 1);
235 throw new ApplicationException ("The thread does not have any reader or writer locks.");
239 void ReleaseReaderLock (int currentCount, int releaseCount)
241 int new_count = currentCount - releaseCount;
244 reader_locks.Remove (Thread.CurrentThreadId);
246 reader_locks [Thread.CurrentThreadId] = new_count;
248 state -= releaseCount;
249 if (state == 0 && !writer_queue.IsEmpty)
250 writer_queue.Pulse ();
254 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
256 public void ReleaseWriterLock()
259 if (!HasWriterLock())
260 throw new ApplicationException ("The thread does not have the writer lock.");
262 ReleaseWriterLock (1);
266 void ReleaseWriterLock (int releaseCount)
268 state += releaseCount;
271 Monitor.PulseAll (this);
273 else if (!writer_queue.IsEmpty)
274 writer_queue.Pulse ();
278 public void RestoreLock(ref LockCookie lockCookie)
281 if (lockCookie.WriterLocks != 0)
282 AcquireWriterLock (-1, lockCookie.WriterLocks);
283 else if (lockCookie.ReaderLocks != 0)
284 AcquireReaderLock (-1, lockCookie.ReaderLocks);
288 public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
292 cookie = GetLockCookie ();
293 if (cookie.WriterLocks != 0) {
298 if (cookie.ReaderLocks != 0)
299 ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
302 // Don't do this inside the lock, since it can cause a deadlock.
303 AcquireWriterLock (millisecondsTimeout);
307 public LockCookie UpgradeToWriterLock(TimeSpan timeout)
309 int ms = CheckTimeout (timeout);
310 return UpgradeToWriterLock (ms);
313 LockCookie GetLockCookie ()
315 LockCookie cookie = new LockCookie (Thread.CurrentThreadId);
318 cookie.WriterLocks = -state;
320 object locks = reader_locks [Thread.CurrentThreadId];
321 if (locks != null) cookie.ReaderLocks = (int)locks;
326 bool HasWriterLock ()
328 return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
331 private int CheckTimeout (TimeSpan timeout)
333 int ms = (int) timeout.TotalMilliseconds;
336 throw new ArgumentOutOfRangeException ("timeout",
337 "Number must be either non-negative or -1");