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.
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.