There are several issues here.
Simple first. Yes, reading and writing a logical variable is an atomic operation. (clarification: I mean that the read and write operations themselves are atomic operations for Boolean, not read and write operations, which, of course, will generate two operations that together will not be atomic)
However, if you do not take additional steps, the compiler can optimize such reads and writes or move operations around, which may cause your code to work differently than you plan.
Marking the field as volatile means that the operations will not be optimized, the directive basically says that the compiler should never accept the value in this field, the same as the previous one, even if it just read it in the previous instruction.
However, on multi-core and multi-core machines, different cores and the processor may have a different meaning for the field in your cache, and thus you add a lock { } clause or something else that creates a memory barrier. This ensures that the field value is consistent across all cores. In addition, reading and writing will not go past the memory barrier in the code, which means that you have predictability in where operations occur.
So, if you suspect or know that this field will be written and read from several streams, I would definitely add blockage and instability in the mix.
Please note that I am not an expert in multithreading, I can keep my own, but I usually program defensively. There it may (I would suggest that this is very likely) that you can implement something that does not use locking (there are many loose constructions), but, unfortunately, I have not enough experience in this topic to handle these things. So my advice is to add both the lock clause and the volatile directive.
Lasse VΓ₯gsΓ¦ther Karlsen
source share