[Windows] thread discussion -- interlocked and readwrite locks for. Net Thread Synchronization

Source: Internet
Author: User
Tags net thread

Abstract: this series is intended to record knowledge points of windwos threads, including thread basics, thread scheduling, thread synchronization, TLS, and thread pool.

This article describes static interlocked classes and readwrite locks.

Interlocked in. net

The interlocked series of methods provide simple types of atomic operations (operations that will not be interrupted), so this is also a multi-threaded shared variable to prevent conflicts and contention.

For example, the following method increments the integer I in an atomic way:

 
Int I = 0; interlocked. increment (Ref I );

It also includes add, exchange, compareexchange, decrement, read, and some generic versions. If you have used the built-in interlock functions of Windows APIs, you may have discovered that the interlocked class only encapsulates Windows API calls. In the [windows] thread mantalk-atomic access to thread synchronization, the significance and usage of interlocked functions are described in detail. NET and Windows API versions are listed as follows:

. Net API Description
Interlocked. Add Interlockedexchangeadd Add a variable
Interlocked. Increment Interlockedincrement Incremental variable
Interlocked. Decrement Interlockeddecrement Decrease variable
Interlocked. Exchange Interlockedexchange Assign values to variables
Interlocked. compareexchange Interlockedcompareexchange Assign values to variables after comparison (parameter 1 and parameter 3 are compared. If they are the same, assign parameter 2 to parameter 1)

In addition, the Windows API provides initializeslisthead/interlockedpushentryslist/interlockedpopentryslist/interlockedflushslist/querydepthslist to build a single-chain table stack. For details, see Windows core programming --- interlocked atomic access functions

For interlocked. compareexchange, I sawArticle: The famous double check lock technology. The general idea of this article is that when an object is created using the new keyword, it may first assign the reference value to the target variable and then call the constructor. Therefore, in Singleton mode, the "dual Detection Technology" may have hidden bugs. Finally, the author proposed an alternative solution using interlocked. compareexchange, which was copied here:

 
Internal sealed class mysingleton {Private Static mysingleton s_value = NULL; public static mysingleton getmysingleton () {If (s_value! = NULL) return s_value; mysingleton temp = new mysingleton (); interlocked. compareexchange (ref s_value, temp, null); Return s_value ;}}

 

Readerwriterlock in. net

Sometimes shared resources should be differentiated between read and write, because the multi-thread reading is often allowed at the same time, because this will not cause confusion; other threads are not allowed to read or write data only when writing is required .. Net readerwriterlock and readerwriterlockslim provide us with a lock to distinguish between read and write. This method is generally more efficient than monitor in some cases. The readerwriterlockslim class is recommended in msdn. The explanation is that readerwriterlockslim uses a simple rule to process recursive calls and better support for Lock upgrade mechanisms, and can better avoid deadlocks, it is more efficient than readerwriterlock. Because the two are very similar, we will give a brief discussion on readerwriterlockslim.

First, we should try to avoid multiple requests for a lock in the same thread. A typical case is recursive call, because it is prone to deadlock. Therefore, the default no-argument constructor of readerwriterlockslim does not allow recursion. Of course, you can also set to allow recursion:

 
Public readerwriterlockslim (lockrecursionpolicy recursionpolicy)

For the readerwriterlockslim lock, a thread attempts to obtain the lock in three modes:

    • Read mode: Read mode, indicating that the thread attempts to read shared resources without writing. Readerwriterlockslim. enterreadlock \ readerwriterlockslim. tryenterreadlock
    • Write mode: Write mode, indicating that the thread tries to write to the shared resource. Readerwriterlockslim. enterwritelock \ readerwriterlockslim. tryenterwritelock
    • Upgradeable read mode: Read mode, but may be upgraded to a write lock in the future. Readerwriterlockslim. enterupgradeablereadlock \ readerwriterlockslim. tryenterupgradeablereadlock

Without considering the Lock of recursive requests from the same thread:

    • At the same time, only one thread can obtain the write lock. When a thread acquires the write lock, other threads cannot obtain any type of lock;
    • Only one upgradeable read lock is allowed at a time. When a thread obtains an upgradeable read lock, other threads can only obtain the read lock;
    • Read locks can be obtained by multiple threads at the same time, except for the above two cases;

Read lock upgrade

At the same time, only one thread can obtain the upgradeable read lock. When the thread that obtains the upgradeable read lock tries to obtain the write lock, it can call enterwritelock. If a thread does not release the write lock, enterwritelock will be blocked until all the read locks are released, and the thread trying to obtain the read locks will also be blocked (write locks are not considered here, because since the read locks can be upgraded, there must be no write locks ), this is a bit like "Close the door and let the dog in, but let the dog in. :)

Please refer to the example on msdn to understand readwriterlockslim: http://msdn.microsoft.com/zh-cn/library/system.threading.readerwriterlockslim.aspx

Readerwriterlockslim and slim read/write locks

The read/write lock synchronization method provided by Windows API is introduced in the SLIM read/write lock of [windows] thread-thread synchronization. The following table compares the two APIs:

. Net API Description
Readerwriterlockslim Construction Initializesrwlock  
Readerwriterlockslim. enterwritelock Acquiresrwlockexclusive  
Readerwriterlockslim. tryenterwritelock --  
Readerwriterlockslim. exitwritelock Releasesrwlockexclusive  
Readerwriterlockslim. enterreadlock Acquiresrwlockshared  
Readerwriterlockslim. tryenterreadlock --  
Readerwriterlockslim. exitreadlock Releasesrwlockshared  
Readerwriterlockslim. enterupgradeablereadlock --  
Readerwriterlockslim. tryenterupgradeablereadlock --  
Readerwriterlockslim. exitupgradeablereadlock --  
-- Condition_variable API supports conditional variables
Recursive features -- . NET provides Recursion

As shown in the preceding table, the. NET version has the following features:

    • Provides the corresponding tryxxx Method
    • Provides the upgradeable write lock feature
    • Provides recursive features
    • Conditional Variable usage not provided

Labor fruit, reproduced please indicate the source: http://www.cnblogs.com/P_Chou/archive/2012/07/24/interlocked-and-slimlock-in-net-thread-sync.html

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.