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 LockQueue writer_queue;
50 private Hashtable reader_locks;
51 private int writer_lock_owner;
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 state = lockCookie.ReaderLocks;
178 reader_locks [Thread.CurrentThreadId] = state;
180 Monitor.PulseAll (this);
183 // MSDN: A thread does not block when downgrading from the writer lock,
184 // even if other threads are waiting for the writer lock
188 public LockCookie ReleaseLock()
192 cookie = GetLockCookie ();
193 if (cookie.WriterLocks != 0)
194 ReleaseWriterLock (cookie.WriterLocks);
195 else if (cookie.ReaderLocks != 0) {
196 ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
202 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
203 public void ReleaseReaderLock()
206 if (HasWriterLock ()) {
207 ReleaseWriterLock ();
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);
218 throw new ApplicationException ("The thread does not have any reader or writer locks.");
222 void ReleaseReaderLock (int currentCount, int releaseCount)
224 int new_count = currentCount - releaseCount;
227 reader_locks.Remove (Thread.CurrentThreadId);
229 reader_locks [Thread.CurrentThreadId] = new_count;
231 state -= releaseCount;
232 if (state == 0 && !writer_queue.IsEmpty)
233 writer_queue.Pulse ();
236 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
237 public void ReleaseWriterLock()
240 if (!HasWriterLock())
241 throw new ApplicationException ("The thread does not have the writer lock.");
243 ReleaseWriterLock (1);
247 void ReleaseWriterLock (int releaseCount)
249 state += releaseCount;
252 Monitor.PulseAll (this);
254 else if (!writer_queue.IsEmpty)
255 writer_queue.Pulse ();
259 public void RestoreLock(ref LockCookie lockCookie)
262 if (lockCookie.WriterLocks != 0)
263 AcquireWriterLock (-1, lockCookie.WriterLocks);
264 else if (lockCookie.ReaderLocks != 0)
265 AcquireReaderLock (-1, lockCookie.ReaderLocks);
269 public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
273 cookie = GetLockCookie ();
274 if (cookie.WriterLocks != 0) {
279 if (cookie.ReaderLocks != 0)
280 ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
283 // Don't do this inside the lock, since it can cause a deadlock.
284 AcquireWriterLock (millisecondsTimeout);
288 public LockCookie UpgradeToWriterLock(TimeSpan timeout)
290 int ms = CheckTimeout (timeout);
291 return UpgradeToWriterLock (ms);
294 LockCookie GetLockCookie ()
296 LockCookie cookie = new LockCookie (Thread.CurrentThreadId);
299 cookie.WriterLocks = -state;
301 object locks = reader_locks [Thread.CurrentThreadId];
302 if (locks != null) cookie.ReaderLocks = (int)locks;
307 bool HasWriterLock ()
309 return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
312 private int CheckTimeout (TimeSpan timeout)
314 int ms = (int) timeout.TotalMilliseconds;
317 throw new ArgumentOutOfRangeException ("timeout",
318 "Number must be either non-negative or -1");