In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "case analysis of C# atomic operation". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought slowly and deeply. Let's study and learn "C# atomic operation case analysis"!
Knowledge point competition condition
Contention occurs when two or more threads access shared data and try to change it at the same time. The part of shared data that they rely on is called competitive conditions.
Data contention is one of the competitive conditions, which may lead to memory damage or uncertainty.
Thread synchronization
If there are N threads that perform an operation, when one thread is performing the operation, the other threads must wait in turn, which is thread synchronization.
The occurrence of a race condition in a multithreaded environment is usually caused by not performing the correct synchronization.
CPU time slice and context switching
A time slice (timeslice) is a microcosmic period of CPU time assigned by the operating system to each running process.
First of all, the kernel allocates equal initial time slices to each process, and then each process executes the corresponding time in turn. When all processes are in a state where the time slices are exhausted, the kernel will recalculate and allocate time slices to each process, and so on.
Please refer to: https://zh.wikipedia.org/wiki/%E6%97%B6%E9%97%B4%E7%89%87
Context switching (Context Switch), also known as process switching or task switching, refers to CPU switching from one process or thread to another.
When an interrupt (Interrupt) is received, the CPU must exchange context. There is a performance loss when context switching is carried out. Blockage
Blocking state means that a thread is in a waiting state. When a thread is in a blocking state, it takes up as little CPU time as possible.
When a thread changes from a running state (Runing) to a blocked state (WaitSleepJoin), the operating system allocates the CPU time slice occupied by this thread to another thread. When the thread returns to running state (Runing), the operating system reassigns the CPU time slice.
Context switching occurs when CPU time slices are allocated.
Kernel mode and user mode
Only the operating system can switch threads and suspend threads, so blocking threads are handled by the operating system, which is called kernel mode (kernel-mode).
Sleep (), Join (), etc., all use kernel mode to block threads and achieve thread synchronization (waiting).
Context switching occurs when a thread waits in kernel mode. This is suitable for operations that take a long time to wait, which reduces a lot of CPU time loss.
If the thread only needs to wait for a very small amount of time, the context switching cost of blocking the thread will be high, so we can use spin to achieve thread synchronization, this method is called user mode (user-mode).
Interlocked class
Provides atomic operations for variables shared by multiple threads.
Using the Interlocked class, you can avoid race conditions without blocking threads (lock, Monitor).
The Interlocked class is static, so let's first take a look at the common methods of Interlocked:
The method uses CompareExchange () to compare whether the two numbers are equal, and if so, replace the first value. Decrement () decrements the value of the specified variable in the form of an atomic operation and stores the result. Exchange () is set to the specified value and returns the original value in the form of an atomic operation. Increment () increments the value of the specified variable in the form of an atomic operation and stores the result. Add () sums two numbers and replaces the first integer, which is done as an atomic operation. Read () returns a value loaded in the form of an atomic operation. 1, a problem occurs
Question:
Assignment and some simple mathematical operations in C # are not atomic operations and may cause problems due to the influence of multithreaded environment.
We can use lock and Monitor to solve these problems, but is there any easier way?
First, let's write the following code:
Private static int sum = 0; public static void AddOne () {for (int I = 0; I)
< 100_0000; i++) { sum += 1; } } 这个方法的工作完成后,sum 会 +100。 我们在 Main 方法中调用: static void Main(string[] args) { AddOne(); AddOne(); AddOne(); AddOne(); AddOne(); Console.WriteLine("sum = " + sum); } 结果肯定是 5000000,无可争议的。 但是这样会慢一些,如果作死,要多线程同时执行呢? 好的,Main 方法改成如下: static void Main(string[] args) { for (int i = 0; i < 5; i++) { Thread thread = new Thread(AddOne); thread.Start(); } Thread.Sleep(TimeSpan.FromSeconds(2)); Console.WriteLine("sum = " + sum); } 笔者运行一次,出现了 sum = 2633938 我们将每次运算的结果保存到数组中,截取其中一段发现: 87578758876087608760876187628763876487658766876687688769 多个线程使用同一个变量进行操作时,并不知道此变量已经在其它线程中发生改变,导致执行完毕后结果不符合期望。 我们可以通过下面这张图来解释:Therefore, there is a need for atomic operations, and at some point only one thread must be able to perform an operation. The above operation refers to the process of reading, calculating, and writing.
Of course, we can use lock or Monitor to solve the problem, but this will result in a large performance loss.
At this point, Interlocked works. For some simple operations, Interlocked can achieve atomic operations.
Atomicity can be solved through a variety of locks. At present, we have learned lock and Monitor, and now we will learn more about the implementation of locks. Now we will learn about Interlocked.
2meme Interlocked.Increment ()
Used for self-increment operations.
Let's modify the AddOne method:
Public static void AddOne () {for (int I = 0; I < 100 million; iTunes +) {Interlocked.Increment (ref sum);}}
Then run it, and you'll find that the result is sum = 5000000, that's right.
Indicates that Interlocked can perform atomic operations on simple value types.
Interlocked.Increment () is incremental, while Interlocked.Decrement () is decreasing. 3Gen Interlocked.Exchange ()
Interlocked.Exchange () implements the assignment operation.
This method has multiple overloads, so let's take a look at one of them:
Public static int Exchange (ref int location1, int value)
It means to assign value to location1 and then return the value before the location1 was changed.
Test:
Static void Main (string [] args) {int a = 1; int b = 5; / / 1 int result1 = Interlocked.Exchange (ref a, 2) before change; Console.WriteLine ($"a new value a = {a} | result1 = {result1}"); Console.WriteLine () / / before the change, int result2 b is 5 int result2 = Interlocked.Exchange (ref a, b); Console.WriteLine ($"a new value a = {a} | b will not change b = {b} | the value before an is result2 = {result2}");}
In addition, Exchange () also overloads the reference type:
Exchange (T, T) 4Gen Interlocked.CompareExchange ()
One of the overloads:
Public static int CompareExchange (ref int location1, int value, int comparand)
Compares whether two 32-bit signed integers are equal, and if so, replaces the first value.
If the values in comparand and location1 are equal, the value is stored in location1. Otherwise, no action is performed.
Check it out, it's a comparison between location1 and comparand!
Examples of use are as follows:
Static void Main (string [] args) {int location1 = 1; int value = 2; int comparand = 3; Console.WriteLine ("before running:"); Console.WriteLine ($"location1 = {location1} | value = {value} | comparand = {comparand}"); Console.WriteLine ("when location1! = comparand") Int result = Interlocked.CompareExchange (ref location1, value, comparand); Console.WriteLine ($"location1 = {location1} | value = {value} | comparand = {comparand} | the pre-location1 value {result}"); Console.WriteLine ("when location1 = = comparand"); comparand = 1; result = Interlocked.CompareExchange (ref location1, value, comparand) Console.WriteLine ($"location1 = {location1} | value = {value} | comparand = {comparand} | the value before the location1 change {result}");} 5Gen Interlocked.add ()
Sum two 32-bit integers and use and replace the first integer, which is done as an atomic operation.
Public static int Add (ref int location1, int value)
Valid only for int or long.
Going back to the multithreaded summation problem in the first section, replace Interlocked.Increment () with Interlocked.Add ().
Static void Main (string [] args) {for (int I = 0; I < 5; iTunes +) {Thread thread = new Thread (AddOne); thread.Start ();} Thread.Sleep (TimeSpan.FromSeconds (2)); Console.WriteLine ("sum =" + sum);} private static int sum = 0 Public static void AddOne () {for (int I = 0; I < 10000000; iTunes +) {Interlocked.Add (ref sum,1);}} 6Magna Interlocked.Read ()
Returns a 64-bit value loaded as an atomic operation.
The Read method is not required on 64-bit systems because 64-bit read operations are already atomic. On 32-bit systems, 64-bit read operations are not atomic unless performed using Read.
Public static long Read (ref long location)
That means it can only be used on a 32-bit system.
Thank you for your reading, the above is the content of "C# atomic operation example analysis". After the study of this article, I believe you have a deeper understanding of the problem of C# atomic operation example analysis. The specific use of the situation also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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: 0
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.