BT

A Replacement for .NET's Flawed ReaderWriterLock

by Jonathan Allen on Mar 05, 2007 |
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.
 

Hello stranger!

You need to Register an InfoQ account or 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

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2013 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT