ReaderWriterLock.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 int writer_lock_owner;
  46. private LockQueue writer_queue;
  47. private Hashtable reader_locks;
  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. if (lockCookie.WriterLocks != 0)
  155. state++;
  156. else {
  157. state = lockCookie.ReaderLocks;
  158. reader_locks [Thread.CurrentThreadId] = state;
  159. if (readers > 0) {
  160. Monitor.PulseAll (this);
  161. }
  162. }
  163. // MSDN: A thread does not block when downgrading from the writer lock,
  164. // even if other threads are waiting for the writer lock
  165. }
  166. }
  167. public LockCookie ReleaseLock()
  168. {
  169. LockCookie cookie;
  170. lock (this) {
  171. cookie = GetLockCookie ();
  172. if (cookie.WriterLocks != 0)
  173. ReleaseWriterLock (cookie.WriterLocks);
  174. else if (cookie.ReaderLocks != 0) {
  175. ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
  176. }
  177. }
  178. return cookie;
  179. }
  180. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  181. public void ReleaseReaderLock()
  182. {
  183. lock (this) {
  184. if (HasWriterLock ()) {
  185. ReleaseWriterLock ();
  186. return;
  187. }
  188. else if (state > 0) {
  189. object read_lock_count = reader_locks [Thread.CurrentThreadId];
  190. if (read_lock_count != null) {
  191. ReleaseReaderLock ((int)read_lock_count, 1);
  192. return;
  193. }
  194. }
  195. throw new ApplicationException ("The thread does not have any reader or writer locks.");
  196. }
  197. }
  198. void ReleaseReaderLock (int currentCount, int releaseCount)
  199. {
  200. int new_count = currentCount - releaseCount;
  201. if (new_count == 0)
  202. reader_locks.Remove (Thread.CurrentThreadId);
  203. else
  204. reader_locks [Thread.CurrentThreadId] = new_count;
  205. state -= releaseCount;
  206. if (state == 0 && !writer_queue.IsEmpty)
  207. writer_queue.Pulse ();
  208. }
  209. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  210. public void ReleaseWriterLock()
  211. {
  212. lock (this) {
  213. if (!HasWriterLock())
  214. throw new ApplicationException ("The thread does not have the writer lock.");
  215. ReleaseWriterLock (1);
  216. }
  217. }
  218. void ReleaseWriterLock (int releaseCount)
  219. {
  220. state += releaseCount;
  221. if (state == 0) {
  222. if (readers > 0) {
  223. Monitor.PulseAll (this);
  224. }
  225. else if (!writer_queue.IsEmpty)
  226. writer_queue.Pulse ();
  227. }
  228. }
  229. public void RestoreLock(ref LockCookie lockCookie)
  230. {
  231. lock (this) {
  232. if (lockCookie.WriterLocks != 0)
  233. AcquireWriterLock (-1, lockCookie.WriterLocks);
  234. else if (lockCookie.ReaderLocks != 0)
  235. AcquireReaderLock (-1, lockCookie.ReaderLocks);
  236. }
  237. }
  238. public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
  239. {
  240. LockCookie cookie;
  241. lock (this) {
  242. cookie = GetLockCookie ();
  243. if (cookie.WriterLocks != 0) {
  244. state--;
  245. return cookie;
  246. }
  247. if (cookie.ReaderLocks != 0)
  248. ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
  249. }
  250. // Don't do this inside the lock, since it can cause a deadlock.
  251. AcquireWriterLock (millisecondsTimeout);
  252. return cookie;
  253. }
  254. public LockCookie UpgradeToWriterLock(TimeSpan timeout)
  255. {
  256. int ms = CheckTimeout (timeout);
  257. return UpgradeToWriterLock (ms);
  258. }
  259. LockCookie GetLockCookie ()
  260. {
  261. LockCookie cookie = new LockCookie (Thread.CurrentThreadId);
  262. if (HasWriterLock())
  263. cookie.WriterLocks = -state;
  264. else {
  265. object locks = reader_locks [Thread.CurrentThreadId];
  266. if (locks != null) cookie.ReaderLocks = (int)locks;
  267. }
  268. return cookie;
  269. }
  270. bool HasWriterLock ()
  271. {
  272. return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
  273. }
  274. private int CheckTimeout (TimeSpan timeout)
  275. {
  276. int ms = (int) timeout.TotalMilliseconds;
  277. if (ms < -1)
  278. throw new ArgumentOutOfRangeException ("timeout",
  279. "Number must be either non-negative or -1");
  280. return ms;
  281. }
  282. }
  283. }