Home >Backend Development >C#.Net Tutorial >Tips for using Interlocked for atomic operations in C#
What are atomic operations?
Atom originally means "the smallest particle that cannot be further divided", while atomic operation means "one or a series of operations that cannot be interrupted" . In C#, when multiple threads operate on a variable at the same time, we should use atomic operations to prevent the value obtained by multiple threads from being not the latest value.
For example: int result = 0;
Multi-thread A is executing result(0)+1
Multi-thread B is executing result(0)+1 at the same time
Then the final result is 1 or 2, this is It's hard to say. If two threads calculate at the same time in the CPU, the result obtained is 1, which is obviously not what we want. Of course, you can use locks to ensure the uniqueness of multi-threaded execution, but its performance is far inferior to atomic operations.
Use Interlocked for atomic operations:
Use the Interlocked class provided by .NET to perform atomic operations on some data. It looks like a lock, but it is not a lock. Its atomic operations are based on the CPU itself. It is non-blocking, so it is more efficient than lock.
The following uses C# code to demonstrate atomic operations:
class Program { //全局变量 private static int _result; //Main方法 static void Main(string[] args) { //运行后按住Enter键数秒,对比使用Interlocked.Increment(ref _result);与 _result++;的不同 while (true) { Task[] _tasks = new Task[100]; int i = 0; for (i = 0; i < _tasks.Length; i++) { _tasks[i] = Task.Factory.StartNew((num) => { var taskid = (int)num; Work(taskid); }, i); } Task.WaitAll(_tasks); Console.WriteLine(_result); Console.ReadKey(); } } //线程调用方法 private static void Work(int TaskID) { for (int i = 0; i < 10; i++) { //_result++; Interlocked.Increment(ref _result); } } }
Comment the last two lines of code when running the above code _result++; and Interlocked.Increment(ref _result); and then run one of the lines. After running, hold down the Enter key and run for a few seconds. You can see the difference between the two.
At this point, the role of Interlocked is reflected. Download the sample source code of this article: Interlocked_Sample.
Other instructions on atomic operations: When executing assignment instructions on a 32-bit CPU, the maximum width of data transmission is 4 bytes. Therefore, as long as the read and write operations are less than 4 bytes, the 32-bit CPU is an atomic operation. Therefore, operations of types such as bool and int are themselves atomic operations. The atomic operation method provided by Interlocked is completed by encapsulating functional CPU instructions at the bottom layer.
The above is the technique of using Interlocked for atomic operations in C# introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!