When is ReaderWriterLockSlim better than a simple lock?

后端 未结 10 1884
孤街浪徒
孤街浪徒 2020-11-29 16:16

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          


        
10条回答
  •  情歌与酒
    2020-11-29 16:48

    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.

提交回复
热议问题