C # Multithreading: Using the ReaderWriterLock class for multi-user read/single-user write synchronization

Source: Internet
Author: User

C # Multithreading: Using the ReaderWriterLock class for multi-user read/single-user write synchronization-mile-blog Park
Http://www.cnblogs.com/lhws/archive/2014/03/31/3636757.html


    • Summary: C # provides the System.Threading.ReaderWriterLock class to accommodate multi-user read/single-user write scenarios. This class implements the following functions: If a resource is not locked by a write operation, then any thread can lock the resource for read operations, and there is no limit to the number of read operation locks, that is, multiple threads can lock the resource at the same time to read the data.

Problems with synchronization control using monitor or mutex: this is always inefficient because the exclusive access model does not allow any form of concurrent access. Many times, applications access resources with read operations and relatively few write operations. To address this problem, C # provides a System.Threading.ReaderWriterLock class to accommodate multi-user read/single-user write scenarios. This class implements the following functions: If a resource is not locked by a write operation, then any thread can lock the resource for read operations, and there is no limit to the number of read operation locks, that is, multiple threads can lock the resource at the same time to read the data. If a resource is not added to any read or write lock, then one and only one thread can add write locks to the resource to write to the data. The simple thing to say is that a read operation lock is a shared lock that allows multiple threads to read data simultaneously; a write operation Lock is an exclusive lock, and at the same time, only one thread is allowed to write.

The sample code is as follows:

usingSystem;usingSystem.Threading;namespaceprocesstest{classProgram {//Resources        Static intTheresource =0; //read, write operation Lock        StaticReaderWriterLock RWL =NewReaderWriterLock (); Static voidMain (string[] args) {            //Create 2 read operations threads, 2 write threads, and start aThread TR0 =NewThread (NewThreadStart (Read)); Thread TR1=NewThread (NewThreadStart (Read)); Thread TR2=NewThread (NewThreadStart (Write)); Thread TR3=NewThread (NewThreadStart (Write)); Tr0.            Start (); TR1.            Start (); TR2.            Start (); TR3.            Start (); //wait for the thread to finish executingtr0.            Join (); TR1.            Join (); TR2.            Join (); TR3.            Join ();        System.Console.ReadKey (); }        //Read Data        Static voidRead () { for(inti =0; I <3; i++)            {                Try                {                    //Request read Operation Lock, if the read operation lock is not acquired within 1000ms, discardRwl. AcquireReaderLock ( +); Console.WriteLine ("start reading data, Theresource = {0}", Theresource); Thread.Sleep (Ten); Console.WriteLine ("read Data end, Theresource = {0}", Theresource); //release read operation LockRWL.                Releasereaderlock (); }                Catch(applicationexception) {//get processing of read lock failure                }            }        }        //Write Data        Static voidWrite () { for(inti =0; I <3; i++)            {                Try                {                    //Write operation Lock is requested, if the write lock is not acquired within 1000ms, discardRwl. AcquireWriterLock ( +); Console.WriteLine ("start writing data, Theresource = {0}", Theresource); //Add theresource to 1theresource++; Thread.Sleep ( -); Console.WriteLine ("end of Write data, Theresource = {0}", Theresource); //Release the write operation LockRWL.                Releasewriterlock (); }                Catch(applicationexception) {//failed to get write operation Lock                }            }        }    }}

In the example above, 2 read threads and 2 write threads were created, alternating between read and write operations. Running results such as:

Observing the results of the operation, it is easy to see that the read operation lock is a shared lock that allows multiple threads to read the data simultaneously; The write operation Lock is an exclusive lock, allowing only one thread to write.

If a thread acquires a read operation lock and, in the middle of a read operation, wants to raise the lock level and turn it into a write lock, the ReaderWriterLock class's upgradetowriterlock (int timeOut) method can be called. The method returns a LockCookie value that holds the state of the UpgradeToWriterLock method call to the front lock. After the write operation is complete, you can call the Downgradefromwriterlock (LockCookie LockCookie) method, which is based on the value of the LockCookie parameter passed in. Restores the thread lock to the state before the UpgradeToWriterLock method call. For specific usage, you can view MSDN for an example.

C # Multithreading: Using the ReaderWriterLock class for multi-user read/single-user write synchronization

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.