C# Interlocked Question.

Asked 2 years ago, Updated 2 years ago, 54 views

Hello, everyone~

While looking at the c# code, there's a part that uses Interlocked If you search, it is a command that supports 1:1 with the machine language

CompareExchange: Compare two targets and set the specified value if the values are the same, otherwise no operation is performed.

Decision: Decreases and stores the value of the specified variable.

Exchange : Sets the variable to the specified value.

Increment: Increase and store the value of the specified variable.

It says that, but I don't understand, so I want a more detailed explanation. For example, in the case of Increment, what variable is the specified variable talking about and what role does it play when it increases?

Please reply. (__)

c# .net

2022-09-22 20:22

1 Answers

You need to understand the multi-threaded environment first.

Multi-threads are implemented by dividing the CPU very finely, allowing multiple threads to share the same CPU. (Even if you have multiple CPUs, there are only a limited number of CPU resources available at the same time, so if you look at a particular CPU, you have to share them.)

Here,

If you look at a specific thread at some point,

The problem is that commands like i = i + 1 that we think are not actually organized into one command at the machine language level.

When two threads share a variable called i, sometimes you need to ensure that the value of i changes. This means that thread switching should occur while changing the i value.

Think of it as interlocked. The functions of Compare, Increment, and Declaration are safe for thread switching values to compare and change in a multi-threaded environment. You do not need to use it unless it is a shared variable between threads.


2022-09-22 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.