Today I was reading about something on SO and stumbled to this note about volatile keyword in C#, it seemed to be nice simple explanation of widely misunderstood term so I am sharing it here.
A good example is say you have 2 threads, one which always writes to a variable (say
queueLength
), and one which always reads from that same variable.
If
queueLength
is not volatile, thread A may write 5 times, but thread B may see those writes as being delayed (or even potentially in the wrong order).
A solution would be to lock, but you could also in this situation use volatile. This would ensure that thread B will always see the most up-to-date thing that thread A has written. Note however that this logic only works if you have writers who never read, and readers who never write, and if the thing you're writing is an atomic value. As soon as you do a single read-modify-write, you need to go to Interlocked operations or use a Lock.
I got this at below URL