Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock mechanism for Queue<T> during Enqueue and Dequeue

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)
} 
like image 621
G33kKahuna Avatar asked Dec 28 '22 04:12

G33kKahuna


2 Answers

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.

like image 140
LBushkin Avatar answered Jan 14 '23 21:01

LBushkin


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.

like image 43
jason Avatar answered Jan 14 '23 21:01

jason