What is the point in Max (Threading.Interlocked.Increment (Offset), Offset - 1)?

I have seen the code snippet mentioned several times now, what is the point Max(a+1, a-1)? At first I thought that this could prevent underflow, but it really doesn't make sense not to prevent overflow in this case.

+3
source share
4 answers

As you already mentioned, maybe they are trying to detect when it Offsetwraps to zero (or goes negative) and keeps it tied to the maximum value for any type Offset. Or they may try to cope with a situation where Offset"at the same time" increases in several threads (or something else).

In any case, this is an erroneous code.

If they try to detect / prevent wrapping to zero or a negative value, too many increments will cause a problem. If they try to figure it out Offsetwhile increasing at the same time, I’m not sure what problem they are really trying to solve or how they are trying to solve it.

Here are the problems:

As John Skeet says :

- Offset , .

, Offset volatile, Offset , , Max() Offset ( ). , , Offset, .

, Offset - ( , , ). Offset . Max(), , , .

Max(Threading.Interlocked.Increment(Offset), Offset - 1)

, ( ), - .


, Google , , (?) # VB.NET. ( ). , Offset , , ( "", ). Offset++ ( , , # Offset++ VB.NET - . http://www.telerik.com/community/forums/open-source-projects/code-converter/added-value.aspx#307755). Offset++ , , , .

, : ", Interlocked.Increment()".

+4

, - (, ) # -VB.NET- . .

: Yessss, ! # VB.NET:

int i;
i++;
+5

, , Max(a, a-1) - Interlocked.Increment. , Interlocked.Increment Offset-1.

- Offset , .

,

Math.Max(Interlocked.Increment(Offset), Offset-1)

Interlocked.Increment ref. :

Math.Max(Interlocked.Increment(ref Offset), Offset-1)

( , ...)

, , . , - .

+2

Interlocked.Increment(a) a. a++, . , , , , . . MSDN.

, , .

+1

Source: https://habr.com/ru/post/1706677/


All Articles