Home Backend Development C#.Net Tutorial Tips for using Interlocked for atomic operations in C#

Tips for using Interlocked for atomic operations in C#

Dec 15, 2016 pm 02:17 PM
Atomic operations

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

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);

}

}

}

Copy after login


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)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use atomic operations in C++ to ensure thread safety? How to use atomic operations in C++ to ensure thread safety? Jun 05, 2024 pm 03:54 PM

Thread safety can be guaranteed by using atomic operations in C++, using std::atomic template class and std::atomic_flag class to represent atomic types and Boolean types respectively. Atomic operations are performed through functions such as std::atomic_init(), std::atomic_load(), and std::atomic_store(). In the actual case, atomic operations are used to implement thread-safe counters to ensure thread safety when multiple threads access concurrently, and finally output the correct counter value.

Database atomic operation method in MySQL Database atomic operation method in MySQL Jun 15, 2023 pm 08:36 PM

MySQL is a popular relational database management system (RDBMS) used to manage various types of data. In the database, an atomic operation refers to an operation that cannot be interrupted during execution. These operations are either all executed successfully or all fail, and only part of the operation is not executed. This is ACID (atomicity, consistency). , isolation, persistence) principle. In MySQL, you can use the following methods to implement atomic operations on the database. Transactions in MySQL

How to solve cache consistency issues in C++ development How to solve cache consistency issues in C++ development Aug 22, 2023 am 10:00 AM

How to solve the cache consistency problem in C++ development In C++ development, the cache consistency problem is a common and important challenge. When threads in a multithreaded program execute on different processors, each processor has its own cache, and there may be data inconsistencies between these caches. This data inconsistency can lead to unexpected errors and undefined behavior of the program. Therefore, solving the cache consistency problem in C++ development is very critical. In C++, there are multiple ways to solve the cache coherency problem

How to perform atomic operations using AtomicInteger function in Java How to perform atomic operations using AtomicInteger function in Java Jun 26, 2023 pm 05:03 PM

When writing multi-threaded applications, it is very important to consider thread safety. Ensuring thread safety, enabling multiple threads to work together, and improving program running efficiency is an issue worthy of full consideration. Java provides many atomic operation functions, including the atomic integer operation function - AtomicInteger. AtomicInteger is an atomic class in Java that can implement atomic operations on an integer variable. The so-called atomic operation means that there can only be

What are atomic operations? An in-depth analysis of atomic operations in go What are atomic operations? An in-depth analysis of atomic operations in go Mar 28, 2023 pm 07:04 PM

In some of our previous articles related to the sync package, we should have also discovered that atomic operations are used in many places. Today let’s take an in-depth look at the principles, usage scenarios, usage, etc. of atomic operations in go.

How do atomic operations in Java ensure data consistency in concurrent programming? How do atomic operations in Java ensure data consistency in concurrent programming? May 03, 2024 am 11:45 AM

Atomic operations ensure data consistency when multiple threads access shared variables concurrently, by executing a series of operations atomically. For example, the AtomicInteger class in Java provides atomic operations, allowing counters to be updated atomically, ensuring that counter values ​​are always correct and consistent, thereby simplifying code and improving performance. However, atomic operations are not omnipotent. For complex concurrency scenarios, locks or other synchronization mechanisms still need to be used, and they are only applicable to basic data types. It is recommended to use concurrent collection classes for reference types.

Java thread synchronization and mutual exclusion: let your program dance in the concurrent world Java thread synchronization and mutual exclusion: let your program dance in the concurrent world Feb 19, 2024 pm 07:33 PM

In computer science, concurrent programming is when a program can perform multiple tasks simultaneously. It is often used to fully utilize the computing power of multi-core processors and plays an important role in areas such as user interface, network communication, and database operations. However, concurrent programming also brings some challenges, the most important of which is how to ensure data consistency and program correctness when multiple threads access shared resources simultaneously. Java provides rich thread synchronization and mutual exclusion mechanisms to help developers solve challenges in concurrent programming. These mechanisms mainly include locks, atomic operations and the volatile keyword. Locks are used to protect shared resources. They allow one thread to monopolize a shared resource when accessing it, preventing other threads from accessing it at the same time, thus avoiding data inconsistency and program crashes.

Atomic operations in C++ memory management Atomic operations in C++ memory management May 03, 2024 pm 12:57 PM

Atomic operations are critical for managing shared memory in a multi-threaded environment, ensuring that accesses to memory are independent of each other. The C++ standard library provides atomic types, such as std::atomic_int, and member functions such as load() and store() for performing atomic operations. These operations are either performed in full or not at all, preventing data corruption caused by concurrent access. Practical cases such as lock-free queues demonstrate the practical application of atomic operations. Use fetch_add() to atomically update the head and tail pointers of the queue to ensure the atomicity and consistency of queue operations.

See all articles