I have an implementation of IDictionary<TKey,TValue> , which internally contains n other Dictionary<TKey, TValue> and distributes these inserts by the HashCode key in the invidual sub-dictionaries. With 16 sub-dictionaries, the number of collisions is rather small on a 4-core machine.
For parallel inserts, I blocked the Add method with ReaderWriterLockSlim , blocking only a separate 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(); } }
When inserting elements with four threads, I got only about 32% of the processor and poor performance. Therefore, I replaced ReaderWriterLockSlim with a monitor (i.e. the lock keyword). Currently, CPU utilization is almost 100%, and performance has more than doubled.
My question is: why increase CPU usage? The number of collisions should not change. What does ReaderWriterLock.EnterWriteLock do so many times?
multithreading c # locking
Raauhotz
source share