2
0

ReaderWriterLock.cs 7.6 KB

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