I\'m doing a very silly benchmark on the ReaderWriterLock with this code, where reading happens 4x more often than writting:
class Program
{
static void
My own tests indicate that ReaderWriterLockSlim
has about 5x the overhead as compared to a normal lock
. That means for the RWLS to outperform a plain old lock the following conditions would generally be occurring.
In most real applications these two conditions are not enough to overcome that additional overhead. In your code specifically, the locks are held for such a short period of time that the lock overhead will probably be the dominating factor. If you were to move those Thread.Sleep
calls inside the lock then you would probably get a different result.
Uncontested locks take on the order of microseconds to acquire, so your execution time will be dwarfed by your calls to Sleep
.
You will get better performance with ReaderWriterLockSlim
than a simple lock if you lock a part of code which needs longer time to execute. In this case readers can work in parallel. Acquiring a ReaderWriterLockSlim
takes more time than entering a simple Monitor
. Check my ReaderWriterLockTiny
implementation for a readers-writer lock which is even faster than simple lock statement and offers a readers-writer functionality: http://i255.wordpress.com/2013/10/05/fast-readerwriterlock-for-net/
I guess this is because of the sleeps you have in you reader and writer threads.
Your read thread has a 500tims 50ms sleep which is 25000 Most of the time it is sleeping
When is ReaderWriterLockSlim better than a simple lock?
When you have significantly more reads than writes.
Unless you have multicore hardware (or at least the same as your planned production environment) you won't get a realistic test here.
A more sensible test would be to extend the lifetime of your locked operations by putting a brief delay inside the lock. That way you should really be able to contrast the parallelism added using ReaderWriterLockSlim
versus the serialization implied by basic lock()
.
Currently, the time taken by your operations that are locked are lost in the noise generated by the Sleep calls that happen outside the locks. The total time in either case is mostly Sleep-related.
Are you sure your real-world app will have equal numbers of reads and writes? ReaderWriterLockSlim
is really better for the case where you have many readers and relatively infrequent writers. 1 writer thread versus 3 reader threads should demonstrate ReaderWriterLockSlim
benefits better, but in any case your test should match your expected real-world access pattern.