2

If i write data using many threads into a property e.g: public decimal number;

will using volatile decimal allow me to read the decimal exception safe without using a lock?

Andy x
  • 41
  • 5
  • 2
    No. Read these: [Part 1](https://web.archive.org/web/20161225050237/http://blog.coverity.com/2014/03/12/can-skip-lock-reading-integer) [Part 2](https://web.archive.org/web/20160729162225/http://blog.coverity.com/2014/03/26/reordering-optimizations/). Never use `volatile` (unless you work at Microsoft, but a good number of C# language *designers* say they're not comfortable enough with volatile's semantics to use it). Also, tearing. – canton7 Mar 27 '20 at 16:49
  • Since you're writing to it using a lock why not just use a lock to read from it? – Sean Mar 27 '20 at 16:50
  • 1
    [This answer](https://stackoverflow.com/a/1668984) for the marked duplicate addresses _exactly_ your question, directly and clearly. – Peter Duniho Mar 27 '20 at 17:04
  • 1
    @canton7: Thanks for the link. I need to move those to my blog. – Eric Lippert Mar 27 '20 at 18:24

1 Answers1

3

A decimal can not be marked volatile. You will get a compiler error. The reason is that operations on this type can not be guaranteed to be atomic due to its size.

You can not assume that lock-free read will be safe. It may return a partially written value which may be invalid, and will definitely not be a desired value.

Rotem
  • 21,452
  • 6
  • 62
  • 109
  • oh ok, so even other types that i could set as volatile still aren't safe to read from? – Andy x Mar 27 '20 at 16:56
  • Other types should try to use the `Interlocked` class for reading and writing without `lock`s. – Rotem Mar 27 '20 at 16:57
  • 3
    (note that you need to both read *and* write using `Interlocked` -- you can't use `Interlocked` just for writing, and ignore it for reading) – canton7 Mar 27 '20 at 16:58
  • 1
    @Andyx: You need to clearly define what you mean by "safe to read from". What safety property are you interested in? `volatile` guarantees only a very small number of safety properties; it guarantees *atomicity* because only atomic types may be marked as volatile, and it guarantees that reads will not be moved backwards in time with respect to certain other special effects; that is, it introduces a half fence. If you are not comfortable reasoning about fences then you should do what I do and not use `volatile`. – Eric Lippert Mar 27 '20 at 18:21