Note I tend to write lock-free code so I try to avoid any types of lock where possible. Instead I just use while(true)
loop because I have a lot of CPU power.
According to that http://msdn.microsoft.com/en-us/library/aa691278%28VS.71%29.aspx double
variable update is not atomic.
I'm concerned about two issues:
- if one thread modify variable of field or property and another thread read it at the same time i want to have either previous or new value, but I don't want to receive something strange. I.e. if one thread changes value from 5.5 to 15.15 I want to have in another thread one of these two numbers, but not 5.15 or 15.5 or anything else.
- if one thread already updated value and another thread read it after that I want to receive latest, up to date, value. I was thinking that volatile keyword can help with that but in seems it can't, because "Volatile does not guarantee freshness of a value. It prevents some optimizations, but does not guarantee thread synchronization." as said here are c# primitive arrays volatile?
Questions:
- Am I correct that without synchronization both of these issues may appear?
- If you can give me short example which proves that without synchronization it will not work - that would be nice
- How should I access double field or variable or property to have always real up to date value? Will "synchronization" guarantee "freshness"? What would be the fastest way for that? spinlock or something?
Currently I use a lot of double
and decimal
variables/field/properties in my program and almost everythig works fine, so I really confused because I ofthen access them from different threads without any synchronization and that just works... But now I'm thinking that probably it would be better to use float
to have "built-in syncrhonization"