Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ++ operation atomic in C#?

Tags:

c#

.net

I have multiple threads accessing a single Int32 variable with "++" or "--" operation.

Do we need to lock before accessing it as below?

    lock (idleAgentsLock)
    {
       idleAgents--;  //we should place it here.
    }

Or what consequences will there be if I don't do the locking?

like image 857
smwikipedia Avatar asked Jul 26 '13 02:07

smwikipedia


1 Answers

It is not "atomic", not in the multi-threaded sense. However your lock protects the operation, theoretically at least. When in doubt you can of course use Interlocked.Decrement instead.

like image 76
kprobst Avatar answered Sep 22 '22 21:09

kprobst