Is there any case in which volatile is useful in the context of single-threaded programming? I know it's used to make sure the value of the variable is always actually checked in memory so is there any case in which that value may change (in a ST app) in a way that the app/compiler won't notice?
Asked
Active
Viewed 194 times
3
-
1Not sure about C#, but C's `volatile` is useful even in single threaded applications to denote that a particular region of memory (a variable) might be access externally (e.g. via hardware) and that it shouldn't be cached in the CPU. Not sure if that translates to C#. – Qix - MONICA WAS MISTREATED Feb 04 '16 at 11:35
-
1It's not useful in a singlethreaded app, and it should be avoided in multithreaded apps. You should use locks, memory barriers or Volatile.Read(), Volatile.Write() instead. [Here's an article by Eric Lippert](https://blogs.msdn.microsoft.com/ericlippert/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three/) where he summarises: *I discourage you from ever making a volatile field.*. [And Joe Duffy calls volatile "Evil"...](http://joeduffyblog.com/2010/12/04/sayonara-volatile/) – Matthew Watson Feb 04 '16 at 11:41
-
I'm not sure of this at all. we are not taking int oconsideration multi processed application where `IntPtr` may not be volatile, but it may point to an array of bytes which represents itself a pointer , and that value might be changed. somehting like int** ptr = &ptr, the C# version, where ptr might be changed from another process – David Haim Feb 04 '16 at 11:51
1 Answers
1
No, it's not necessary. It is used to synchronize the memory content between the threads which in case you have only one it doesn't make sense.

Zbynek Vyskovsky - kvr000
- 18,186
- 3
- 35
- 43