. Net – multithreading and Boolean
I have a class that contains Boolean fields like this:
public class MyClass { private bool boolVal; public bool BoolVal { get { return boolVal; } set { boolVal = value; } } }
You can use this property to read and write this field from many threads My question is, should I use locking statements to block getters and setters? Or should I just use the volatile keyword and save the lock? Or should I completely ignore multithreading because I get and set Boolean atoms?
to greet,
Solution
Here are a few questions
Simplicity first Yes, reading and writing Boolean variables is an atomic operation (clarification: I mean that the read-write operation itself is an atomic operation of Boolean value, not a read-write operation. Of course, two operations will be generated, and these operations will not be atomic together)
However, unless you take additional steps, the compiler may optimize such read and write operations, or move operations, which may make your code different from your operations
Marking a field as volatile means that the operation will not be optimized. This instruction basically means that the compiler should not assume that the value in this field is the same as the previous field, even if it only reads it in the previous instruction
However, on multi-core and multi CPU computers, different cores and CPUs may have different field values in their caches, so you add a lock {} clause or any other clause that enforces memory barriers This ensures that field values are consistent across cores In addition, reads and writes do not exceed the memory barrier in the code, which means that you can predict where operations occur
Therefore, if you suspect or know that this field will be written to and read from multiple threads, I will certainly add locking and volatile
Please note that I'm not an expert in multithreading. I can have my own, but I usually program in defense Maybe (I think it's possible) you can implement something that doesn't use locks (there are many lock free constructs), but unfortunately I don't have enough experience in this topic to deal with these things So my suggestion is to add a lock clause and a volatile instruction