0

Hello I have a sample of code but I'm not sure how to lock the variables in Parallel.For, my understanding is that many threads at the same are using the variables used inside the for.

int VVA=0;

for (int i = 0; i < result.Count; i++)
        {
            if (result[i] == 'a')
                va++;                
        };

//Result with normal for: 5000

Parallel.For(0, result.Count, index => 
        {
            if (result[index] == 'a')
                va++;
            
            Interlocked.Add(ref VVA, va); 
        });

//Result with parallel for: 43565646 (something like that)

What is missing here? thanks in advance!

Vmax
  • 119
  • 6
  • What is `va` initialized as? What is being printed? What is the value of `result.Count`? – Patrick Roberts Mar 09 '21 at 02:47
  • 2
    `Interlocked.Add` is thread-safe, but your `va++` is not, because `va` is declared outside of the loop body. So you're adding `va` to `VVA`, but you've mutated `va` in a non thread-safe way, so it's not clear what its value will be at a given point. – ProgrammingLlama Mar 09 '21 at 02:50
  • Hi... result is a list... and count can be whatever, for example 50000 elements. Va starts with 0 @PatrickRoberts – Vmax Mar 09 '21 at 03:04
  • @John I want the same resutl as the normal for in the parallel for. how can be that possible? – Vmax Mar 09 '21 at 03:06
  • 4
    @Vmax Use the thread-safe `Increment` method instead of `va++;`. Note that your second method is just logically incorrect anyway, and you'd get the wrong result even without involving multi-threading. – ProgrammingLlama Mar 09 '21 at 03:07
  • 1
    It's correct it should be: otherVar = Interlocked.Increment(ref va); and otherVar will have the right amount. @John thanks a lot! – Vmax Mar 09 '21 at 04:13

0 Answers0