File: ReaderWriterLockSlim.cs

package info (click to toggle)
mono 2.6.7-5.1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 327,344 kB
  • ctags: 413,649
  • sloc: cs: 2,471,883; xml: 1,768,594; ansic: 350,665; sh: 13,644; makefile: 8,640; perl: 1,784; asm: 717; cpp: 209; python: 146; sql: 81; sed: 16
file content (564 lines) | stat: -rw-r--r-- 15,517 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//
// System.Threading.ReaderWriterLockSlim.cs
//
// Authors:
//   Miguel de Icaza (miguel@novell.com) 
//   Dick Porter (dick@ximian.com)
//   Jackson Harper (jackson@ximian.com)
//   Lluis Sanchez Gual (lluis@ximian.com)
//   Marek Safar (marek.safar@gmail.com)
//
// Copyright 2004-2008 Novell, Inc (http://www.novell.com)
// Copyright 2003, Ximian, Inc.
//
// NoRecursion code based on the blog post from Vance Morrison:
//   http://blogs.msdn.com/vancem/archive/2006/03/28/563180.aspx
//
// Recursion code based on Mono's implementation of ReaderWriterLock.
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Diagnostics;
using System.Threading;

namespace System.Threading {

	//
	// This implementation is based on the light-weight
	// Reader/Writer lock sample from Vance Morrison's blog:
	//
	// http://blogs.msdn.com/vancem/archive/2006/03/28/563180.aspx
	//
	// And in Mono's ReaderWriterLock
	//
	[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
	[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
	public class ReaderWriterLockSlim : IDisposable {
		sealed class LockDetails
		{
			public int ThreadId;
			public int ReadLocks;
		}

		// Are we on a multiprocessor?
		static readonly bool smp;
		
		// Lock specifiation for myLock:  This lock protects exactly the local fields associted
		// instance of MyReaderWriterLock.  It does NOT protect the memory associted with the
		// the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
		int myLock;

		// Who owns the lock owners > 0 => readers
		// owners = -1 means there is one writer, Owners must be >= -1.  
		int owners;
		Thread upgradable_thread;
		Thread write_thread;
		
		// These variables allow use to avoid Setting events (which is expensive) if we don't have to. 
		uint numWriteWaiters;        // maximum number of threads that can be doing a WaitOne on the writeEvent 
		uint numReadWaiters;         // maximum number of threads that can be doing a WaitOne on the readEvent
		uint numUpgradeWaiters;      // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1). 
		
		// conditions we wait on. 
		EventWaitHandle writeEvent;    // threads waiting to aquire a write lock go here.
		EventWaitHandle readEvent;     // threads waiting to aquire a read lock go here (will be released in bulk)
		EventWaitHandle upgradeEvent;  // thread waiting to upgrade a read lock to a write lock go here (at most one)

		//int lock_owner;

		// Only set if we are a recursive lock
		//Dictionary<int,int> reader_locks;

		readonly LockRecursionPolicy recursionPolicy;
		LockDetails[] read_locks = new LockDetails [8];
		
		static ReaderWriterLockSlim ()
		{
			smp = Environment.ProcessorCount > 1;
		}
		
		public ReaderWriterLockSlim ()
		{
			// NoRecursion (0) is the default value
		}

		public ReaderWriterLockSlim (LockRecursionPolicy recursionPolicy)
		{
			this.recursionPolicy = recursionPolicy;
			
			if (recursionPolicy != LockRecursionPolicy.NoRecursion){
				//reader_locks = new Dictionary<int,int> ();
				throw new NotImplementedException ("recursionPolicy != NoRecursion not currently implemented");
			}
		}

		public void EnterReadLock ()
		{
			TryEnterReadLock (-1);
		}

		public bool TryEnterReadLock (int millisecondsTimeout)
		{
			if (millisecondsTimeout < Timeout.Infinite)
				throw new ArgumentOutOfRangeException ("millisecondsTimeout");
			
			if (read_locks == null)
				throw new ObjectDisposedException (null);

			if (Thread.CurrentThread == write_thread)
				throw new LockRecursionException ("Read lock cannot be acquired while write lock is held");

			EnterMyLock ();

			LockDetails ld = GetReadLockDetails (Thread.CurrentThread.ManagedThreadId, true);
			if (ld.ReadLocks != 0) {
				ExitMyLock ();
				throw new LockRecursionException ("Recursive read lock can only be aquired in SupportsRecursion mode");
			}
			++ld.ReadLocks;
			
			while (true){
				// Easy case, no contention
				// owners >= 0 means there might be readers (but no writer)
				if (owners >= 0 && numWriteWaiters == 0){
					owners++;
					break;
				}
				
				// If the request is to probe.
				if (millisecondsTimeout == 0){
					ExitMyLock ();
					return false;
				}

				// We need to wait.  Mark that we have waiters and wait.  
				if (readEvent == null) {
					LazyCreateEvent (ref readEvent, false);
					// since we left the lock, start over. 
					continue;
				}

				if (!WaitOnEvent (readEvent, ref numReadWaiters, millisecondsTimeout))
					return false;
			}
			ExitMyLock ();
			
			return true;
		}

		public bool TryEnterReadLock (TimeSpan timeout)
		{
			return TryEnterReadLock (CheckTimeout (timeout));
		}

		//
		// TODO: What to do if we are releasing a ReadLock and we do not own it?
		//
		public void ExitReadLock ()
		{
			EnterMyLock ();

			if (owners < 1) {
				ExitMyLock ();
				throw new SynchronizationLockException ("Releasing lock and no read lock taken");
			}

			--owners;
			--GetReadLockDetails (Thread.CurrentThread.ManagedThreadId, false).ReadLocks;

			ExitAndWakeUpAppropriateWaiters ();
		}

		public void EnterWriteLock ()
		{
			TryEnterWriteLock (-1);
		}
		
		public bool TryEnterWriteLock (int millisecondsTimeout)
		{
			if (millisecondsTimeout < Timeout.Infinite)
				throw new ArgumentOutOfRangeException ("millisecondsTimeout");

			if (read_locks == null)
				throw new ObjectDisposedException (null);

			if (IsWriteLockHeld)
				throw new LockRecursionException ();

			EnterMyLock ();

			LockDetails ld = GetReadLockDetails (Thread.CurrentThread.ManagedThreadId, false);
			if (ld != null && ld.ReadLocks > 0) {
				ExitMyLock ();
				throw new LockRecursionException ("Write lock cannot be acquired while read lock is held");
			}

			while (true){
				// There is no contention, we are done
				if (owners == 0){
					// Indicate that we have a writer
					owners = -1;
					write_thread = Thread.CurrentThread;
					break;
				}

				// If we are the thread that took the Upgradable read lock
				if (owners == 1 && upgradable_thread == Thread.CurrentThread){
					owners = -1;
					write_thread = Thread.CurrentThread;
					break;
				}

				// If the request is to probe.
				if (millisecondsTimeout == 0){
					ExitMyLock ();
					return false;
				}

				// We need to wait, figure out what kind of waiting.
				
				if (upgradable_thread == Thread.CurrentThread){
					// We are the upgradable thread, register our interest.
					
					if (upgradeEvent == null){
						LazyCreateEvent (ref upgradeEvent, false);

						// since we left the lock, start over.
						continue;
					}

					if (numUpgradeWaiters > 0){
						ExitMyLock ();
						throw new ApplicationException ("Upgrading lock to writer lock already in process, deadlock");
					}
					
					if (!WaitOnEvent (upgradeEvent, ref numUpgradeWaiters, millisecondsTimeout))
						return false;
				} else {
					if (writeEvent == null){
						LazyCreateEvent (ref writeEvent, true);

						// since we left the lock, retry
						continue;
					}
					if (!WaitOnEvent (writeEvent, ref numWriteWaiters, millisecondsTimeout))
						return false;
				}
			}

			Debug.Assert (owners == -1, "Owners is not -1");
			ExitMyLock ();
			return true;
		}

		public bool TryEnterWriteLock (TimeSpan timeout)
		{
			return TryEnterWriteLock (CheckTimeout (timeout));
		}

		public void ExitWriteLock ()
		{
			EnterMyLock ();

			if (owners != -1) {
				ExitMyLock ();
				throw new SynchronizationLockException ("Calling ExitWriterLock when no write lock is held");
			}

			//Debug.Assert (numUpgradeWaiters > 0);
			if (upgradable_thread == Thread.CurrentThread)
				owners = 1;
			else
				owners = 0;
			write_thread = null;
			ExitAndWakeUpAppropriateWaiters ();
		}

		public void EnterUpgradeableReadLock ()
		{
			TryEnterUpgradeableReadLock (-1);
		}

		//
		// Taking the Upgradable read lock is like taking a read lock
		// but we limit it to a single upgradable at a time.
		//
		public bool TryEnterUpgradeableReadLock (int millisecondsTimeout)
		{
			if (millisecondsTimeout < Timeout.Infinite)
				throw new ArgumentOutOfRangeException ("millisecondsTimeout");

			if (read_locks == null)
				throw new ObjectDisposedException (null);

			if (IsUpgradeableReadLockHeld)
				throw new LockRecursionException ();

			if (IsWriteLockHeld)
				throw new LockRecursionException ();

			EnterMyLock ();
			while (true){
				if (owners == 0 && numWriteWaiters == 0 && upgradable_thread == null){
					owners++;
					upgradable_thread = Thread.CurrentThread;
					break;
				}

				// If the request is to probe
				if (millisecondsTimeout == 0){
					ExitMyLock ();
					return false;
				}

				if (readEvent == null){
					LazyCreateEvent (ref readEvent, false);
					// since we left the lock, start over.
					continue;
				}

				if (!WaitOnEvent (readEvent, ref numReadWaiters, millisecondsTimeout))
					return false;
			}

			ExitMyLock ();
			return true;
		}

		public bool TryEnterUpgradeableReadLock (TimeSpan timeout)
		{
			return TryEnterUpgradeableReadLock (CheckTimeout (timeout));
		}
	       
		public void ExitUpgradeableReadLock ()
		{
			EnterMyLock ();
			Debug.Assert (owners > 0, "Releasing an upgradable lock, but there was no reader!");
			--owners;
			upgradable_thread = null;
			ExitAndWakeUpAppropriateWaiters ();
		}

		public void Dispose ()
		{
			read_locks = null;
		}

		public bool IsReadLockHeld {
			get { return RecursiveReadCount != 0; }
		}
		
		public bool IsWriteLockHeld {
			get { return RecursiveWriteCount != 0; }
		}
		
		public bool IsUpgradeableReadLockHeld {
			get { return RecursiveUpgradeCount != 0; }
		}

		public int CurrentReadCount {
			get { return owners & 0xFFFFFFF; }
		}
		
		public int RecursiveReadCount {
			get {
				EnterMyLock ();
				LockDetails ld = GetReadLockDetails (Thread.CurrentThread.ManagedThreadId, false);
				int count = ld == null ? 0 : ld.ReadLocks;
				ExitMyLock ();
				return count;
			}
		}

		public int RecursiveUpgradeCount {
			get { return upgradable_thread == Thread.CurrentThread ? 1 : 0; }
		}

		public int RecursiveWriteCount {
			get { return write_thread == Thread.CurrentThread ? 1 : 0; }
		}

		public int WaitingReadCount {
			get { return (int) numReadWaiters; }
		}

		public int WaitingUpgradeCount {
			get { return (int) numUpgradeWaiters; }
		}

		public int WaitingWriteCount {
			get { return (int) numWriteWaiters; }
		}

		public LockRecursionPolicy RecursionPolicy {
			get { return recursionPolicy; }
		}
		
#region Private methods
		void EnterMyLock ()
		{
			if (Interlocked.CompareExchange(ref myLock, 1, 0) != 0)
				EnterMyLockSpin ();
		}

		void EnterMyLockSpin ()
		{

			for (int i = 0; ;i++) {
				if (i < 3 && smp)
					Thread.SpinWait (20);    // Wait a few dozen instructions to let another processor release lock. 
				else 
					Thread.Sleep (0);        // Give up my quantum.  

				if (Interlocked.CompareExchange(ref myLock, 1, 0) == 0)
					return;
			}
		}

		void ExitMyLock()
		{
			Debug.Assert (myLock != 0, "Exiting spin lock that is not held");
			myLock = 0;
		}

		bool MyLockHeld { get { return myLock != 0; } }

		/// <summary>
		/// Determines the appropriate events to set, leaves the locks, and sets the events. 
		/// </summary>
		private void ExitAndWakeUpAppropriateWaiters()
		{
			Debug.Assert (MyLockHeld);

			// First a writing thread waiting on being upgraded
			if (owners == 1 && numUpgradeWaiters != 0){
				// Exit before signaling to improve efficiency (wakee will need the lock)
				ExitMyLock ();
				// release all upgraders (however there can be at most one). 
				upgradeEvent.Set ();
				//
				// TODO: What does the following comment mean?
				// two threads upgrading is a guarenteed deadlock, so we throw in that case. 
			} else if (owners == 0 && numWriteWaiters > 0) {
				// Exit before signaling to improve efficiency (wakee will need the lock)
				ExitMyLock ();
				// release one writer. 
				writeEvent.Set ();
			}
			else if (owners >= 0 && numReadWaiters != 0) {
				// Exit before signaling to improve efficiency (wakee will need the lock)
				ExitMyLock ();
				// release all readers.
				readEvent.Set();
			} else
				ExitMyLock();
		}

		/// <summary>
		/// A routine for lazily creating a event outside the lock (so if errors
		/// happen they are outside the lock and that we don't do much work
		/// while holding a spin lock).  If all goes well, reenter the lock and
		/// set 'waitEvent' 
		/// </summary>
		void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent)
		{
			Debug.Assert (MyLockHeld);
			Debug.Assert (waitEvent == null);
			
			ExitMyLock ();
			EventWaitHandle newEvent;
			if (makeAutoResetEvent) 
				newEvent = new AutoResetEvent (false);
			else 
				newEvent = new ManualResetEvent (false);

			EnterMyLock ();

			// maybe someone snuck in. 
			if (waitEvent == null)
				waitEvent = newEvent;
		}

		/// <summary>
		/// Waits on 'waitEvent' with a timeout of 'millisceondsTimeout.  
		/// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
		/// </summary>
		bool WaitOnEvent (EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
		{
			Debug.Assert (MyLockHeld);

			waitEvent.Reset ();
			numWaiters++;

			bool waitSuccessful = false;

			// Do the wait outside of any lock 
			ExitMyLock();      
			try {
				waitSuccessful = waitEvent.WaitOne (millisecondsTimeout, false);
			} finally {
				EnterMyLock ();
				--numWaiters;
				if (!waitSuccessful)
					ExitMyLock ();
			}
			return waitSuccessful;
		}
		
		static int CheckTimeout (TimeSpan timeout)
		{
			try {
				return checked((int) timeout.TotalMilliseconds);
			} catch (System.OverflowException) {
				throw new ArgumentOutOfRangeException ("timeout");				
			}
		}

		LockDetails GetReadLockDetails (int threadId, bool create)
		{
			int i;
			LockDetails ld;
			for (i = 0; i < read_locks.Length; ++i) {
				ld = read_locks [i];
				if (ld == null)
					break;

				if (ld.ThreadId == threadId)
					return ld;
			}

			if (!create)
				return null;

			if (i == read_locks.Length)
				Array.Resize (ref read_locks, read_locks.Length * 2);
				
			ld = read_locks [i] = new LockDetails ();
			ld.ThreadId = threadId;
			return ld;
		}
#endregion
	}
}