Johnny_D
Johnny_D

Reputation: 4652

C# ReaderWriter lock thread release priority

I've recently bumped into multithreading perfomance issue, and started to investigate how to optimize current code.

The most suitable solution for my issue is using readerwriter lock, but this article of Jeffrey Richter made me have some doubt in using this kind of locks. I have much more readers then writers, but writer changes should be applied as fast as possible.

Does this behavior still remain in .net 4.5 version of readerwriter lock? I mean priority of reader threads over writer threads?

Upvotes: 0

Views: 1168

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109822

Firstly, you should use the new ReaderWriterLockSlim class, which is more efficient than the older one, and also avoids many cases of potential deadlock.

Secondly, it is not possible to avoid a writer having to wait for any thread that already has a read (or write) lock at the time that the writer wants to write - that's a fundamental part of the requirements of a reader/writer lock.

Thirdly, writers DO have precedence over readers when they are waiting for a write lock.

From the documentation for ReaderWriterLockSlim.EnterWriteLock():

If other threads have entered the lock in read mode, a thread that calls the EnterWriteLock method blocks until those threads have exited read mode.

When there are threads waiting to enter write mode, additional threads that try to enter read mode or upgradeable mode block until all the threads waiting to enter write mode have either timed out or entered write mode and then exited from it.

In this respect it seems to differ from ReaderWriterLock - this looks like one of the things that has been fixed.

This is about the best you can get. The key thing is for the readers to keep their locks for the shortest time possible.

Also note that neither ReaderWriterLock nor ReaderWriterLockSlim support inter-process locks.

Upvotes: 2

Related Questions