A usage scenario of ReaderWriterLock's UpgradeToWriterLock method, lockmode. upgrade

Source: Internet
Author: User

A usage scenario of ReaderWriterLock's UpgradeToWriterLock method, lockmode. upgrade

The advantage of ReaderWriterLock compared with mutex lock is that the Read and Write locks are separated from each other.

Of course, this article focuses not on ReaderWriterLock itself, but on its UpgradeToWriterLock method.

Consider the following scenarios.

There is a Dictionary. Multiple Threads modify and traverse it at the same time. When a thread traverses it (read lock), it needs to Remove the Dictionary based on certain conditions, which may be (less likely, otherwise it will be okay to directly use the read lock. This thread obtains the read lock. if you Remove the Dictionary directly, it will inevitably affect other threads that are also reading the lock. What should we do?

This is the time when the UpgradeToWriterLock method is available! The function of this method is to upgrade the current read lock to a write lock. After the upgrade, the thread will wait for the completion of other read locks, just like obtaining the write lock. Therefore, the next Remove operation is thread-safe. (Remember DowngradeFromWriterLock after the end)

Related Article

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.