Is volatile necessary when using a lock to read/write the variable?
On this line, i defined the state as volatile and the code works fine, but I'm wondering if it really needs to be volatile? Multiple threads can read/write the variable but they always lock the
stateLock
first
https://github.com/AngryCarrot789/SharpPad/blob/ef18f1767eb7e855e5575ff0457bdd793947f973/SharpPad/Utils/RDA/RapidDispatchActionEx.cs#L388 Replies
If all reads and writes are protected by a lock I don't see any reason volatile is needed.
Although in general understanding when and where to use
volatile
is actually quite tricky.I read somewhere that building in release, the value of
state
could just be read once if it's not volatile
But since locks create memory barriers, then maybe it always reads from memory... not sureYes, if you are in a lock then it shouldn't be an issue is my understanding.
Unknown User•9mo ago
Message Not Public
Sign In & Join Server To View
C#'s one is just it prevents reordering of read/write operations and stops the variable being cached right?
I can't remember what C's was but i think it's something like if you access a volatile variable 3 times and write 2 times, it will always do exactly that and won't read/write any caches
Yes, it's pretty much to prevent re-ordering of reads and writes.
Well it also spawns menory barriers on some platforms
Isn't that the same thing?
On systems that require it, inserts a memory barrier that prevents the processor from reordering memory operations as follows: If a read or write appears after this method in the code, the processor cannot move it before this method.