ReaderWriterLock and Collections

  • Thread starter Thread starter pokémon
  • Start date Start date
P

pokémon

Question:

Is this thread-safe:

ReaderWriterLock rwl = new ReaderWriterLock();
Queue q = new Queue();

public int GetCount() {
int val = 0;
try {
rwl.AcquireReaderLock(Timeout.Infinite);
val = q.Count;
} finally {
rwl.ReleaseReaderLock();
}
return val;
}

Or do I need to do:

public int GetCount() {
int val = 0;
try {
rwl.AcquireReaderLock(Timeout.Infinite);
lock(q.SyncRoot) {
val = q.Count;
}
} finally {
rwl.ReleaseReaderLock();
}
return val;
}
 
I think that you're looking for this;

Queue q = Queue.Synchronized( new Queue() );

Otherwise,

If you always acquire some lock on the ReaderWriterLock, there is no need
need to "lock ( q.SyncRoot )", although you'd you'd probably want to make a
queue wrapper class to ensure that this was enforced.
 
Yes, the wrapper is doing the locking, and the Queue object itself is
private and thus hidden from the outsiders that use it.

For some reason, I have shied away from Queue.Synchronized. I can't explain
why, only that it seems less literal to use it for synchronization, than
actually coding the extra lines which make it clear to another developer
what the deal is.

Also, isn't the RWL slightly faster than using the Synchronized wrapper?
 
Back
Top