In Queue, enqueue and dequeue both need a write lock. Why would someone use ReaderWriterLockSlim versus just using lock{}? As an example,
Using ReaderWriterLockSlim
qLock.EnterWriteLock();
try
{
localQ.Enqueue(item); // or localQ.Dequeue(item)
}
finally
{
qLock.ExitWriteLock();
}
Versus lock{}
try
{
lock(qLock) { localQ.Enqueue(item);} // or localQ.Dequeue(item)
}
The use of ReaderWriterLockSlim
is primarily a performance optimization in scenarios where there are many threads reading from a resource often but only a few threads writing to it.
The Monitor class (used by the lock statement) acquires an exclusive lock on the resource - which means that both readers and writers are blocked. In many cases, however, reading is much more frequent than writing. In those scenarios, the use of a reader/writer lock allows multiple readers to enter the locks simultaneously but only one writer at a time (when all queued readers are out).
In your example the a reader/writer lock only makes sense if there is other code that peeks at the queue without dequeing an item ... otherwise all operations are mutating writes, and a lock
statement would be more appropriate.
Well, that would still permit readers to Peek
without requiring a write lock
. It's hard to imagine a scenario where this is practically useful though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With