ReaderWriterLock.cs 8.1 KB

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