3

I have a "unique" type integer. I use it like this:

int unique=0;
public int GetUniqueId()
{
  return unique++;
}

I know I'm being a bit paranoid, but is this an atomic operation, or would it require some form of lock? This function will be used in a extremely concurrent class.

Earlz
  • 62,085
  • 98
  • 303
  • 499

2 Answers2

9

No; this is emphatically not atomic.
x++ compiles to three separate instructions (load, increment, store), which can be interrupted by other threads.

If this will run on multiple threads, you should call Interlocked.Increment(ref unique) (which is atomic) instead.
This call is somewhat slower than a regular increment, much much faster than a full lock.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • And it's things like this that make writing concurrent code extremely scary :) – Earlz Dec 04 '12 at 04:11
  • I thought the x86 instruction set's inc was atomic if memory was aligned? – ta.speot.is Dec 04 '12 at 04:12
  • @ta.speot.is that may be true, but I do know there isn't an atomic `inc` instruction in IL now... So, it may be atomic under x86 in certain JIT compilers, but not guaranteed to be so.. – Earlz Dec 04 '12 at 04:24
  • @ta.speot.is This question indicates that the INC instruction is not atomic: http://stackoverflow.com/questions/10109679/how-come-inc-instruction-of-x86-is-not-atomic – Mike Zboray Dec 04 '12 at 04:29
0

If this method is used by the concurrent threads then you have to handle the concurrency which is achieved by putting the lock.

Jatin Khurana
  • 1,155
  • 8
  • 15