ReaderWriterLock.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. #if NET_2_0
  36. using System.Runtime.InteropServices;
  37. using System.Runtime.ConstrainedExecution;
  38. #endif
  39. namespace System.Threading
  40. {
  41. #if NET_2_0
  42. [ComVisible (true)]
  43. public sealed class ReaderWriterLock: CriticalFinalizerObject
  44. #else
  45. public sealed class ReaderWriterLock
  46. #endif
  47. {
  48. private int seq_num = 1;
  49. private int state;
  50. private int readers;
  51. private LockQueue writer_queue;
  52. private Hashtable reader_locks;
  53. private int writer_lock_owner;
  54. public ReaderWriterLock()
  55. {
  56. writer_queue = new LockQueue (this);
  57. reader_locks = new Hashtable ();
  58. }
  59. public bool IsReaderLockHeld {
  60. #if NET_2_0
  61. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  62. #endif
  63. get {
  64. lock (this) return reader_locks.ContainsKey (Thread.CurrentThreadId);
  65. }
  66. }
  67. public bool IsWriterLockHeld {
  68. #if NET_2_0
  69. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  70. #endif
  71. get {
  72. lock (this) return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
  73. }
  74. }
  75. public int WriterSeqNum {
  76. get {
  77. lock (this) return seq_num;
  78. }
  79. }
  80. public void AcquireReaderLock (int millisecondsTimeout)
  81. {
  82. AcquireReaderLock (millisecondsTimeout, 1);
  83. }
  84. void AcquireReaderLock (int millisecondsTimeout, int initialLockCount)
  85. {
  86. lock (this) {
  87. if (HasWriterLock ()) {
  88. AcquireWriterLock (millisecondsTimeout, initialLockCount);
  89. return;
  90. }
  91. object nlocks = reader_locks [Thread.CurrentThreadId];
  92. if (nlocks == null)
  93. {
  94. // Not currently holding a reader lock
  95. // Wait if there is a write lock
  96. readers++;
  97. try {
  98. if (state < 0 || !writer_queue.IsEmpty) {
  99. do {
  100. if (!Monitor.Wait (this, millisecondsTimeout))
  101. throw new ApplicationException ("Timeout expired");
  102. } while (state < 0);
  103. }
  104. }
  105. finally {
  106. readers--;
  107. }
  108. reader_locks [Thread.CurrentThreadId] = initialLockCount;
  109. state += initialLockCount;
  110. }
  111. else {
  112. reader_locks [Thread.CurrentThreadId] = ((int)nlocks) + 1;
  113. state++;
  114. }
  115. }
  116. }
  117. public void AcquireReaderLock(TimeSpan timeout)
  118. {
  119. int ms = CheckTimeout (timeout);
  120. AcquireReaderLock (ms, 1);
  121. }
  122. public void AcquireWriterLock (int millisecondsTimeout)
  123. {
  124. AcquireWriterLock (millisecondsTimeout, 1);
  125. }
  126. void AcquireWriterLock (int millisecondsTimeout, int initialLockCount)
  127. {
  128. lock (this) {
  129. if (HasWriterLock ()) {
  130. state--;
  131. return;
  132. }
  133. // wait while there are reader locks or another writer lock, or
  134. // other threads waiting for the writer lock
  135. if (state != 0 || !writer_queue.IsEmpty) {
  136. do {
  137. if (!writer_queue.Wait (millisecondsTimeout))
  138. throw new ApplicationException ("Timeout expired");
  139. } while (state != 0);
  140. }
  141. state = -initialLockCount;
  142. writer_lock_owner = Thread.CurrentThreadId;
  143. seq_num++;
  144. }
  145. }
  146. public void AcquireWriterLock(TimeSpan timeout) {
  147. int ms = CheckTimeout (timeout);
  148. AcquireWriterLock (ms, 1);
  149. }
  150. public bool AnyWritersSince(int seqNum) {
  151. lock (this) {
  152. return (this.seq_num > seqNum);
  153. }
  154. }
  155. public void DowngradeFromWriterLock(ref LockCookie lockCookie)
  156. {
  157. lock (this) {
  158. if (!HasWriterLock())
  159. throw new ApplicationException ("The thread does not have the writer lock.");
  160. state = lockCookie.ReaderLocks;
  161. reader_locks [Thread.CurrentThreadId] = state;
  162. if (readers > 0) {
  163. Monitor.PulseAll (this);
  164. }
  165. // MSDN: A thread does not block when downgrading from the writer lock,
  166. // even if other threads are waiting for the writer lock
  167. }
  168. }
  169. public LockCookie ReleaseLock()
  170. {
  171. LockCookie cookie;
  172. lock (this) {
  173. cookie = GetLockCookie ();
  174. if (cookie.WriterLocks != 0)
  175. ReleaseWriterLock (cookie.WriterLocks);
  176. else if (cookie.ReaderLocks != 0) {
  177. ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
  178. }
  179. }
  180. return cookie;
  181. }
  182. #if NET_2_0
  183. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  184. #endif
  185. public void ReleaseReaderLock()
  186. {
  187. lock (this) {
  188. if (HasWriterLock ()) {
  189. ReleaseWriterLock ();
  190. return;
  191. }
  192. else if (state > 0) {
  193. object read_lock_count = reader_locks [Thread.CurrentThreadId];
  194. if (read_lock_count != null) {
  195. ReleaseReaderLock ((int)read_lock_count, 1);
  196. return;
  197. }
  198. }
  199. throw new ApplicationException ("The thread does not have any reader or writer locks.");
  200. }
  201. }
  202. void ReleaseReaderLock (int currentCount, int releaseCount)
  203. {
  204. int new_count = currentCount - releaseCount;
  205. if (new_count == 0)
  206. reader_locks.Remove (Thread.CurrentThreadId);
  207. else
  208. reader_locks [Thread.CurrentThreadId] = new_count;
  209. state -= releaseCount;
  210. if (state == 0 && !writer_queue.IsEmpty)
  211. writer_queue.Pulse ();
  212. }
  213. #if NET_2_0
  214. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  215. #endif
  216. public void ReleaseWriterLock()
  217. {
  218. lock (this) {
  219. if (!HasWriterLock())
  220. throw new ApplicationException ("The thread does not have the writer lock.");
  221. ReleaseWriterLock (1);
  222. }
  223. }
  224. void ReleaseWriterLock (int releaseCount)
  225. {
  226. state += releaseCount;
  227. if (state == 0) {
  228. if (readers > 0) {
  229. Monitor.PulseAll (this);
  230. }
  231. else if (!writer_queue.IsEmpty)
  232. writer_queue.Pulse ();
  233. }
  234. }
  235. public void RestoreLock(ref LockCookie lockCookie)
  236. {
  237. lock (this) {
  238. if (lockCookie.WriterLocks != 0)
  239. AcquireWriterLock (-1, lockCookie.WriterLocks);
  240. else if (lockCookie.ReaderLocks != 0)
  241. AcquireReaderLock (-1, lockCookie.ReaderLocks);
  242. }
  243. }
  244. public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
  245. {
  246. LockCookie cookie;
  247. lock (this) {
  248. cookie = GetLockCookie ();
  249. if (cookie.WriterLocks != 0) {
  250. state--;
  251. return cookie;
  252. }
  253. if (cookie.ReaderLocks != 0)
  254. ReleaseReaderLock (cookie.ReaderLocks, cookie.ReaderLocks);
  255. }
  256. // Don't do this inside the lock, since it can cause a deadlock.
  257. AcquireWriterLock (millisecondsTimeout);
  258. return cookie;
  259. }
  260. public LockCookie UpgradeToWriterLock(TimeSpan timeout)
  261. {
  262. int ms = CheckTimeout (timeout);
  263. return UpgradeToWriterLock (ms);
  264. }
  265. LockCookie GetLockCookie ()
  266. {
  267. LockCookie cookie = new LockCookie (Thread.CurrentThreadId);
  268. if (HasWriterLock())
  269. cookie.WriterLocks = -state;
  270. else {
  271. object locks = reader_locks [Thread.CurrentThreadId];
  272. if (locks != null) cookie.ReaderLocks = (int)locks;
  273. }
  274. return cookie;
  275. }
  276. bool HasWriterLock ()
  277. {
  278. return (state < 0 && Thread.CurrentThreadId == writer_lock_owner);
  279. }
  280. private int CheckTimeout (TimeSpan timeout)
  281. {
  282. int ms = (int) timeout.TotalMilliseconds;
  283. if (ms < -1)
  284. throw new ArgumentOutOfRangeException ("timeout",
  285. "Number must be either non-negative or -1");
  286. return ms;
  287. }
  288. }
  289. }