The locking mechanism for the <T> queue during Enqueue and Dequeue

In the queue, in the queue, and in deactivation, a write lock is required. Why is someone using ReaderWriterLockSlim against using lock {}? As an example,

Using ReaderWriterLockSlim

qLock.EnterWriteLock(); try { localQ.Enqueue(item); // or localQ.Dequeue(item) } finally { qLock.ExitWriteLock(); } 

Unlike locking {}

 try { lock(qLock) { localQ.Enqueue(item);} // or localQ.Dequeue(item) } 
+4
source share
3 answers

Using ReaderWriterLockSlim is, first of all, performance optimization in scenarios, where there are often many threads reading from a resource, but only a few threads writing to it.

The Monitor class (used by the lock operator) receives an exclusive lock on the resource - this means that both readers and writers are blocked. In many cases, however, reading is much more common than writing. In these scenarios, using read / write locks allows multiple readers to enter locks at the same time, but only one writer at a time (when all readers are not in the queue).

In your example, a read / write lock makes sense only if there is other code that looks into the queue without allocating an object ... otherwise all operations will mutate the records, and the lock statement will be more appropriate.

+5
source

Well, it will still allow Peek readers without having to write a lock . It is difficult to imagine a scenario where it is practically useful.

+3
source

In this case, ReaderWriterLockSlim does not provide any real benefits. You are correct that both Enqueue and Dequeue are write operations and require exclusive write locks.

For a collection that has read operations, as most collections do, then ReaderWriterLockSlim will be better than always using lock .

The only slight advantage I could think of was consistency. If ReaderWriterLockSlim used in most cases, because most other collections are used for a large number of readings and several records, then for development and maintenance it is easiest to use ReaderWriterLockSlim everywhere.

+2
source

All Articles