Rob L
Rob L

Reputation: 2372

Is this 'double +=' thread safe?

This line of code is being executed within a Parallel.For(...row => { code });

mechanismScores[row] += cellValue;

The array values and the cellValue are both of type double. Is this thread safe or do I need to do something like...

Interlocked.CompareExchange(ref mechanismScores[row], 
    mechanismScores[row] + cellValue, mechanismScores[row]);

or another solution?

Upvotes: 2

Views: 739

Answers (2)

MeTitus
MeTitus

Reputation: 3428

Whatever type mechanismScores is, it seems to be that is it an object, so a simple lock(mechanismScores) will do. If within the loop that same value can be changed in different contexts than it is not thread safe.

Upvotes: 0

svick
svick

Reputation: 244777

If you have parallel loop where each iteration accesses different item in the array, and no other code is accessing the array at the same time, then your code is thread-safe.

If two iterations could access the same index in the array, you would need some sort of synchronization, either by using a lock or using Interlocked.CompareExchange() properly (as Michael Burr pointed out, your example is not safe).

Upvotes: 6

Related Questions