While you can use spin locks with
recursive programming techniques, you must release the lock before recursing or else suffer a
deadlock.
nNote If you require a reentrant wait mechanism, you can use wait objects that are more structured, such
as the Monitor class, which we cover next, or kernel-based wait objects.
CHAPTER 13 n THREADING 290
Monitor Class
The previous section showed you how to implement a spin lock using the methods of the
Interlocked class. A spin lock is not always the most efficient synchronization mechanism,
especially if you use it in an environment where a wait is almost guaranteed. The thread
scheduler has to continually wake up the thread and allow it to recheck the lock variable. As
mentioned before, a spin lock is ideal when you need a lightweight, non-reentrant synchronization
mechanism and the odds are low that a thread will have to wait in the first place.
When you know the likelihood of waiting is high, you should use a synchronization mechanism
that allows the scheduler to avoid waking the thread until the lock is available. .NET
provides the System.Threading.Monitor class to allow synchronization between threads within
the same process. You can use this class to guard access to certain variables or to gate access
to code that should only be run on one thread at a time.
Pages:
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