Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interlocked.Increment Method by a Certain Number Interval

We have a concurrent, multithreaded program. How would I make a sample number increase by +5 interval every time? Does Interlocked.Increment, have an overload for interval? I don't see it listed.

Microsoft Interlocked.Increment Method

// Attempt to make it increase by 5

private int NumberTest;

for (int i = 1; i <= 5; i++)
{
    NumberTest= Interlocked.Increment(ref NumberTest);
}

This is another question its based off,

C# Creating global number which increase by 1


2 Answers

I think you want Interlocked.Add:

Adds two integers and replaces the first integer with the sum, as an atomic operation.

int num = 0;
Interlocked.Add(ref num, 5);
Console.WriteLine(num);
like image 121
DiplomacyNotWar Avatar answered Nov 04 '25 11:11

DiplomacyNotWar


Adding (i.e +=) is not and cannot be an atomic operation (as you know). Unfortunately, there is no way to achieve this without enforcing a full fence, on the bright-side these are fairly optimised at a low level. However, there are several other ways you can ensure integrity though (especially since this is just an add)

  1. The use of Interlocked.Add (The sanest solution)
  2. Apply exclusive lock (or Moniter.Enter) outside the for loop.
  3. AutoResetEvent to ensure threads doing task one by one (meh sigh).
  4. Create a temp int in each thread and once finished add temp onto the sum under an exclusive lock or similar.
  5. The use of ReaderWriterLockSlim.
  6. Parallel.For thread based accumulation with Interlocked.Increment sum, same as 4.
like image 29
TheGeneral Avatar answered Nov 04 '25 10:11

TheGeneral