C
C#3mo ago
br4kejet

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#L38
8 Replies
mtreit
mtreit3mo ago
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.
br4kejet
br4kejet3mo ago
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 sure
mtreit
mtreit3mo ago
Yes, if you are in a lock then it shouldn't be an issue is my understanding.
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
br4kejet
br4kejet3mo ago
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
mtreit
mtreit3mo ago
Yes, it's pretty much to prevent re-ordering of reads and writes.
Petris
Petris3mo ago
Well it also spawns menory barriers on some platforms
mtreit
mtreit3mo ago
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.