Are basic arithmetic operations in a C # atom

Are basic arithmetic operations safe for threads?

For example, if there is a function ++for a global variable that will be changed from different threads, is it necessary to block it?

for instance

void MyThread() // can have many running instances
{
    aGlobal++;
}

or should he be

void MyThread()
{
    lock( lockerObj)
    {
        aGlobal++;
    }
}
+3
source share
3 answers

The spectrum sums up very well. Section 5.5 "Atomicity of variable links":

: atomic: bool, char, , sbyte, short, ushort, uint, int, float reference. , . , , , , , . , , read-modify-write, , .

:

, Interlocked , , , Monitor.Enter ( lock).

+8

( , 64 +). , , - .

, System.Threading.Interlocked Increment Decrement.

, lock . , , , , .

+2

... System.Threading.Interlocked.Increment(ref int location). , , ( - ) , System.Threading.Interlocked.Increment .

( , ), lock - System.Threading.ReaderWriterLockSlim .

btw - !

0

All Articles