Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The realization principle of lock Syntax Sugar in C #

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "the realization principle of lock grammatical sugar in C#". In daily operation, I believe that many people have doubts about the realization principle of lock grammatical sugar in C#. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "the realization principle of lock grammatical sugar in C#". Next, please follow the editor to study!

Atomic operation

The modified state is either successful and the state changes, or fails and the state remains the same, and the outside can only observe the state before or after the modification, and the state in the middle of the modification cannot be observed.

In .NET, the System.Threading.Interlocked class provides functions for performing atomic operations, which take the reference parameter (ref), the memory address of the variable, and then perform the atomic operation on the value in that memory address.

Lock-free algorithm

Do not use thread locks, but modify the contents of operations to make them meet the conditions of atomic operations

.net provides thread-safe data types that make extensive use of lock-free algorithms to improve access speed (thread locks are still required in some cases):

System.Collections.Consurrent.CurrentBag

System.Collections.Consurrent.CurrentDictionary

System.Collections.Consurrent.CurrentQueue

System.Collections.Consurrent.CurrentStack

Thread lock

There are two operations: acquiring lock (Acquire) and releasing lock (Release). The operation after acquiring the lock and before releasing the lock ensures that only one thread executes at the same time, and the operation content does not need to be changed, so thread lock has strong versatility.

There are different kinds of thread locks. Spin locks, mutex locks, hybrid locks, read-write locks are introduced below.

Spin lock

Spin lock (Spinlock) is the simplest thread lock, which is based on atomic operation.

It uses a numeric value to indicate whether the lock has been acquired, 0 indicates that it has not been acquired, and 1 indicates that it has been acquired.

When acquiring the lock, you will first use the atomic operation to set the value to 1, and then check whether the value before modification is 0. If it is 0, it indicates success, otherwise you will continue to retry until it is successful.

When the lock is released, the value is set to 0, and the other threads that are acquiring the lock will successfully acquire it on the next retry.

The reason for using the atomic operation is that it ensures that multiple threads can change the value from 0 to 1 at the same time, only one thread can observe the pre-modified value as 0, and other threads can observe the pre-modified value as 1.

.net can use the following classes to implement spin locks:

System.Threading.Thread.SpinWait

System.Threading.SpinWait

System.Threading.SpinLock

There is a problem to pay attention to when using a spin lock. The code protected by the spin lock should be executed in a very short time. If the code runs for a long time, other threads that need to acquire the lock will continue to retry and occupy the logic core, affecting other threads to run.

In addition, if the CPU has only one logic core, the spin lock should immediately call the Thread.Yield function to prompt the operating system to switch to another thread when the acquisition fails, because a logic core can only run one thread at a time, and other threads have no chance to run before switching threads, that is, the spin lock has no chance to be released before switching threads.

Mutex lock

Because spin lock is not suitable for long time running, its usage scenario is limited. The more general thread lock is the Mutex based on atomic operation and thread scheduling provided by the operating system.

Like the spin lock, the mutex provided by the operating system has a value indicating whether it has been acquired or not. the difference is that when it fails to acquire the lock, it will not retry again and again, but arrange for the thread to enter the waiting state. The thread object is added to the queue associated with the lock, and when another thread releases the lock, it checks whether there is a thread object in the queue, and if so, notifies the operating system to wake up the thread.

Because the thread in the waiting state is not running, it will not consume CPU resources even if it is not released for a long time, but it may take milliseconds for the thread to enter the waiting state and wake up from the waiting state and schedule to run, which is very long compared to the nanosecond time required for spin lock retry

.net provides the System.Threading.Mutex class, which wraps the mutex provided by the operating system. It is reentrant. The thread that has acquired the lock can perform the operation of acquiring the Su lock again, but the operation of releasing the lock has to be performed the same number of times. The reentrant lock is also called Recursive Lock.

Inside the recursive lock, a counter is used to record the number of entry times. Each time the same thread gets it, it adds 1 and releases it minus 1. After minus 1, the real release operation is performed if the counter becomes 0, which is generally used in multiple functions called within nesting calls.

Another feature of the Mutex class is that it supports cross-process use, and the name can be passed in through the second parameter of the constructor when created.

If one process acquires a lock, another process needs to wait before releasing the lock; if the process acquires the lock but does not call the method to release the lock before exiting, the lock will be automatically released by the operating system, and other processes currently waiting for the lock (the lock will enter the waiting state before the lock is automatically released) will receive an AbandonedMutexException exception

Cross-process locks are usually used to protect resources shared by multiple processes or to prevent multiple starts of programs.

Hybrid lock

When using mutex Mutex, you must create a retyped instance, because the instance contains an unmanaged mutex object, and the developer must call the Dispose function to release unmanaged resources as soon as possible after not using the lock, and the thread will wait immediately after the failure to acquire the lock, so the overall performance is relatively low.

Net provides a more generic and higher performance hybrid lock (Monitor). Objects of any reference type can be used as lock objects. There is no need to create an instance of the specified type in advance, and the unmanaged resources involved are automatically released by the .NET runtime, and there is no need to manually call the release function.

Acquiring and releasing hybrid locks requires the use of functions in the System.Threading.Monitor class

C # provides lock statements to simplify the code obtained and released through the Monitor class

The hybrid lock is characterized by retrying a certain number of times like a spin lock after a failure to acquire the lock, and then arranging the current process to enter the waiting state after a certain number of times (.NET Core 2.1is 30 times).

The advantage of the hybrid lock is that if the first acquisition of the lock fails, but the other thread releases the lock immediately, the current thread can succeed in the next round of retry and does not need to perform millisecond thread scheduling processing; while if the other thread does not release the lock in a short period of time, the thread will wait after the number of retries to avoid consuming CPU resources, so the hybrid lock is suitable for most scenarios

Read-write lock

Read-write lock (ReaderWriterLock) is a thread lock with special purpose, which is suitable for scenarios where reading is frequent and takes a certain amount of time.

Read operations of shared resources can usually be performed at the same time, while ordinary mutexes cannot be executed at the same time, either read or modify operations. If multiple threads acquire mutexes for read operations, then only one thread can perform read operations at the same time, which will affect throughput in frequent read scenarios.

Read-write locks are divided into read locks and write locks. Threads can choose whether to acquire read-write locks or write locks according to the type of operation on shared resources, read locks can be acquired by multiple threads at the same time, write locks cannot be acquired by multiple threads at the same time, and read locks and write locks cannot be acquired by different threads at the same time.

The System.Threading.ReaderWriterLockSlim class provided by .NET implements read-write locks.

Read-write lock is also a hybrid lock (Hybird Lock), which is retried by spin for a certain number of times before entering the waiting state when acquiring the lock.

In addition, it also supports the same thread to acquire a read-write lock first, and then upgrade to a write lock, which is suitable for scenarios where "you need to acquire a read-write lock first, then read the shared data to determine whether it needs to be modified, and then obtain a write lock when you need to modify it".

At this point, the study of "the implementation principle of lock grammatical sugar in C#" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 298

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report