Question:There is a class that has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented. To increment this field, three thread-safe approaches are mentioned below:
A) lock(this.locker) this.counter++;
B) Interlocked.Increment(ref this.counter);
C) Change the access modifier of counter to public volatile
Which statement is incorrect with regards to these approaches?
A All 3 are equivalent and can be used interchangeably.
B Though A is safe to do, it prevents any other threads from executing any other code which is guarded by locker.
C B is the best approach as it effectively does the read, increment, and write in 'one hit' which can't be interrupted.
D C on it's own isn't actually safe at all. The point of volatile is that multiple threads running on multiple CPU's can, and will, cache data and re-order instructions.