4

Should I use static fields and interlocked together, in cases when i need to provide thread safety and atomic operations with static fields, Is static fields are atomic by default? For example:

Interlocked.Increment(ref Factory.DefectivePartsCount);

Thanks.

testCoder
  • 7,155
  • 13
  • 56
  • 75

2 Answers2

4

Yes.

The field (assuming Int32) is atomic, not because it's static but because it's 32 bits.

How ever, Factory.DefectivePartsCount += 1 requires a read and a write action on the variable so the whole operation is not thread-safe.

H H
  • 263,252
  • 30
  • 330
  • 514
  • What does mean 32 bit (32 bit operating system - windows?). If i will using 64 bit system, is operations will be completely atomic? – testCoder Oct 20 '12 at 13:17
  • Yes, when you target 64 bits then an Int64 would be atomic too. But why depend on that? And note, only _single_ operations will be atomic. – H H Oct 20 '12 at 13:19
1

static doesn't guarantee anything in terms of thread-safety. Hence, an increment will still not be atomic even if the variable is static. As such, you will still need to use classic synchronization mechanisms depending on the situation. In your case Interlocked.Increment is fine.

Tudor
  • 61,523
  • 12
  • 102
  • 142