BT

New Early adopter or innovator? InfoQ has been working on some new features for you. Learn more

A Replacement for .NET's Flawed ReaderWriterLock

| by Jonathan Allen Follow 8 Followers on Mar 05, 2007. Estimated reading time: 1 minute |
Visual Studio 2007 will have a new lock called ReaderWriterLockSlim. According to Joe Duffy, in addition to being faster, it solves some of the nastier design flaws of its predecessor.
 
The ReaderWriterLock is known to be broken in some reentrancy cases and has a non-atomic upgrade which required checking the lock's WriterSeqNum.
 
The support upgradeable reads, ReaderWriterLockSlim has a new mode called UpgradeableRead. Only one thread may be in this mode at a time, so threads should quickly determine if the lock should be upgraded to a Write lock or downgraded to a ReadLock. If you downgrade, then the UpgradeableRead should be released immediately afterwards. This makes the design pattern for using the lock somewhat annoying, though it certainly beats deadlocks.
 
By default locks are not reentrant and attempts to recursively acquire a specific lock will result in an exception. Reentrancy can be specifically granted at construction time, presumably at a performance cost.
 
Conversions from Read locks to Write locks are specifically not allowed, as they would result in the same non-atomic upgrade that plagued the original ReaderWriterLock.
 
The ReaderWriterLockSlim isn't perfect however, and there are some serious reliability concerns when using it in hosted environment. For one, it doesn't participate in SQL Server's deadlock detection so you don't want to use it in libraries called from stored procedures. Secondly, thread aborts and out of memory exceptions may corrupt the lock and even peg the CPU. Since thread aborts shouldn't be used anyways and hard out of memory exceptions are always hard to recover from, this won't impact most applications.
 

Rate this Article

Adoption Stage
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Discuss

Login to InfoQ to interact with what matters most to you.


Recover your password...

Follow

Follow your favorite topics and editors

Quick overview of most important highlights in the industry and on the site.

Like

More signal, less noise

Build your own feed by choosing topics you want to read about and editors you want to hear from.

Notifications

Stay up-to-date

Set up your notifications and don't miss out on content that matters to you

BT