Concurrency data structures: Read-write lock ReaderWriterLockSlim classes available in the. NET Framework

Source: Internet
Author: User

turn from; http://www.cnblogs.com/lucifer1982/archive/2008/12/07/1349437.html

ReaderWriterLockSlim class

The new ReaderWriterLockSlim class supports three locking modes: Read,write,upgradeableread. The corresponding methods of these three modes are enterreadlock,enterwritelock,enterupgradeablereadlock respectively. And then the corresponding Tryenterreadlock,tryenterwritelock,tryenterupgradeablereadlock,exitreadlock,exitwritelock, Exitupgradeablereadlock. Read and writer lock modes are straightforward: Read mode is a typical shared lock mode, and any number of threads can acquire locks simultaneously in this mode, while Writer mode is mutex mode, in which only one thread is allowed to enter the lock. Upgradeableread lock mode may be more fresh for most people, but it is well known in the database field.

This new read-write lock class is roughly the same as the monitor class, probably within twice times the Monitor class. And the new lock overrides the write thread to get the lock because the write operation is much less frequent than the read operation. Typically this leads to better scalability. At first, the ReaderWriterLockSlim class was designed with a considerable amount of context in mind. For example, in the early CTP code also provides prefersreaders, Preferswritersandupgrades and Fifo and other competitive strategies. But these strategies, while simple to add, can lead to very complex situations. So Microsoft finally decided to provide a simple model that would work well in most cases.

Update lock for ReaderWriterLockSlim

Now let's discuss the update model in more depth. Upgradeableread lock mode allows for secure updates from Read or Write mode. Remember that the previous ReaderWriterLock update was non-atomic and dangerous (especially if most people didn't realize it at all)? The new read-write lock provided now does not destroy atomicity or cause deadlocks. The new lock allows only one thread to be in Upgradeableread mode at a time.

Once the read-write lock is in upgradeableread mode, the thread can read certain status values to determine whether to downgrade to read mode or upgrade to write mode. Note that this decision should be made as soon as possible: holding the Upgradeableread lock will force any new read requests to wait, even though the existing read operation is still active. Unfortunately, the CLR team removed the two methods of Downgradetoread and Upgradetowrite. If you want to downgrade to a read lock, simply call the EnterReadLock method immediately after the Exitupgradeablereadlock method: This allows the other read and upgradeableread to be completed before they should have been The Upgradeableread lock holds the operation. If you are upgrading to a write lock, simply call the Enterwritelock method: This may wait until no more threads hold the lock in Read mode. Unlike downgrading to read locks, you must call Exitupgradeablereadlock. You do not have to call Exitupgradeablereadlock in Write mode. But in order to be unified, it is best to call it. For example, the following code:

Using system;using system.linq;using System.threading;namespace lucifer.csharp.sample{class Program {privat        E ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim ();            void Sample () {bool isupdated = true;            Rwlock.enterupgradeablereadlock (); try {if (/* ...                    Read the status value to decide whether to update ... */) {rwlock.enterwritelock (); try {//...                     Write status Value ...}                    finally {Rwlock.exitwritelock ();                    }} else {rwlock.enterreadlock ();                    Rwlock.exitupgradeablereadlock ();                    isupdated = false; try {//...                     Read status Value ...}               finally {         Rwlock.exitreadlock (); }}} finally {if (isupdated) RwLock.            Exitupgradeablereadlock (); }        }    }}
Recursive strategy of ReaderWriterLockSlim

Another interesting feature of the new read-write lock is its recursive strategy. By default, all recursive requests are disallowed except for the downgrade to read lock and upgrade to write lock mentioned. This means that you cannot call EnterReadLock two times in a row, and other modes are similar. If you do this, the CLR will throw a lockrecursionexception exception. Of course, you can use the Lockrecursionpolicy.supportsrecursion constructor parameter to enable the read-write lock to support recursive locking. Recursion is not recommended for new development, however, because recursion can lead to unnecessary complications, making your code more prone to deadlocks.

There is a special situation that is never allowed, no matter what recursion strategy you take. This is when a thread holds a read lock and requests a write lock. Microsoft has considered providing such support, but this situation is too easy to lead to deadlocks. So Microsoft eventually abandoned the program.

In addition, this new read-write lock provides a number of properties to determine whether the thread holds the lock under the specified model. such as Isreadlockheld, Iswritelockheld and Isupgradeablereadlockheld. You can also see how many threads are waiting to hold a lock in a particular mode by using properties such as Waitingreadcount,waitingwritecount and Waitingupgradecount. The Currentreadcount property tells you how many concurrent read threads are currently present. Recursivereadcount, Recursivewritecount, and Recursiveupgradecount tell the current number of times that the thread has entered a specific mode lock state.

Summary

This article analyzes the two read-write lock classes available in. NET. However, the new read-write lock ReaderWriterLockSlim class provided by. NET 3.5 eliminates the major problems with the ReaderWriterLock class. Compared with ReaderWriterLock, performance has been greatly improved. Updates are atomic and can greatly avoid deadlocks. There is a clearer recursive strategy. In any case, we should use ReaderWriterLockSlim instead of the ReaderWriterLock class.

Concurrency data structures: Read-write lock ReaderWriterLockSlim classes available in the. NET Framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.