What does atomic mean in C#?
Atomic means that an operation is done without the chance for another thread to come in and do something in the middle of it.
Explanation with Example
Let’s say you have a program with two threads that can both access myClass.Counter. The first thread just loops over these two statements:
myClass.Counter = -1;
myClass.Counter = 0;
The second thread loops and reads the value of myClass.Counter:
long value = myClass.Counter;
if (value < -1 || value > 0)
throw new InvalidOperationException();
If you’re in a 64-bit application, the second thread will never throw: the first thread writes 64 bits at a time, the second thread reads 64 bits at a time. Easy.
But if you’re in a 32-bit application, that might not be true. A write of 64 bits is really two 32-bit writes. A read of 64 bits is really two 32-bit reads.
So what could happen, in terms of thread operation, is:
1: It writes first 32 bits of -1 to MyClass.Counter
1: writes second 32 bits of -1 to MyClass.Counter
1: write first 32 bits of 0 to MyClass.Counter
2: It reads first 32 bits of MyClass.Counter (all 0)
2: reads second 32 bits of MyClass.Counter (all 1)
This is a “torn write“: the first thread didn’t get to complete its write before the contents of what it was writing were read by someone else. You can similarly get a “torn read” if the second thread reads half of the contents and the first thread writes before it gets the second half.
If assignments and reads were atomic, you wouldn’t have to worry about that. The System.Threading.Interlocked class provides access to some atomic reads, exchanges, etc.
Hope you were able to follow the example and context of this post about atomic in c#.
What do you think?
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.