ReaderWriterLockSlim与监控 [英] ReaderWriterLockSlim vs. Monitor

查看:133
本文介绍了ReaderWriterLockSlim与监控的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的IDictionary< TKEY的,TValue> 的实施,国内持有其余n 词典< TKEY的,TValue> 并通过关键invidual子字典的哈希码分配的插入。随着16个子词典,冲突的数量是4芯机器上相当低。

I have an IDictionary<TKey,TValue> implementation that internally holds n other Dictionary<TKey, TValue> and distributes that insertions by the HashCode of the key to the invidual sub-dictionaries. With 16 sub-dictionaries, the number of collisions is pretty low on a 4-core machine.

有关并行插入,我锁定了附加方法以 ReaderWriterLockSlim ,锁定只有个别子词典:

For parallel insertions, i locked the Add-method with a ReaderWriterLockSlim, locking only the individual sub-dictionary:

  public void Add(TKey key, TValue value)
        {
            int poolIndex = GetPoolIndex(key);
            this.locks[poolIndex].EnterWriteLock();
            try
            {
                this.pools[poolIndex].Add(key, value);
            }
            finally
            {
                this.locks[poolIndex].ExitWriteLock();
            }
        }

在四线程插入的项目,我只得到了约32%的CPU使用率和糟糕表现。所以,我通过监视器(即锁定关键字)取代了ReaderWriterLockSlim。
CPU使用率现在近100%,表现超过一倍。

When inserting items with four threads, i only got about 32% cpu usage and bad performance. So i replaced the ReaderWriterLockSlim by a Monitor (i.e., the lock keyword). CPU usage was now at nearly 100% and the performance was more than doubled.

我的问题是:为什么CPU使用率提高?发生碰撞的次数不应该发生了变化。是什么让ReaderWriterLock.EnterWriteLock等待了这么多次?

My question is: Why did the CPU usage increase? The number of collisions should not have changed. What makes ReaderWriterLock.EnterWriteLock wait so many times?

推荐答案

有关只写加载监视器比ReaderWriterLockSlim便宜,但是,如果您模拟读+写负载在哪里读比写大得多,那么ReaderWriterLockSlim应该出来进行监控。

For write-only load the Monitor is cheaper than ReaderWriterLockSlim, however, if you simulate read + write load where read is much greater than write, then ReaderWriterLockSlim should out perform Monitor.

这篇关于ReaderWriterLockSlim与监控的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆