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++; } }
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, , .
:
i++
Interlocked
, Interlocked , , , Monitor.Enter ( lock).
Monitor.Enter
lock
( , 64 +). , , - .
, System.Threading.Interlocked Increment Decrement.
System.Threading.Interlocked
Increment
Decrement
, lock . , , , , .
... System.Threading.Interlocked.Increment(ref int location). , , ( - ) , System.Threading.Interlocked.Increment .
System.Threading.Interlocked.Increment(ref int location)
System.Threading.Interlocked.Increment
( , ), lock - System.Threading.ReaderWriterLockSlim .
System.Threading.ReaderWriterLockSlim
btw - !