Are the basic arithmetic operations Thread safe?
For example, if there is ++ operation on a global variable, which will be modified from different threads, is it necessary to a lock around it?
For example
void MyThread() // can have many running instances
{
aGlobal++;
}
or should it be
void MyThread()
{
lock( lockerObj)
{
aGlobal++;
}
}
The spec sums it up very well. Section 5.5, “Atomicity of variable references”:
Conclusions:
i++) is never atomicInterlockedclass methods to achieve atomicity when it’s not already guaranteedIn cases where
Interlockedfunctionality is not enough there is no other option than to use a synchronization primitive, such asMonitor.Enter(which the compiler also exposes through thelockstatement).