Multithreading and Booleans

I have a class that contains a boolean field like this:

public class MyClass { private bool boolVal; public bool BoolVal { get { return boolVal; } set { boolVal = value; } } } 

A field can be read and written from many threads using a property. My question is, should I clamp the getter and setter with the lock statement? Or should I just use the volatile keyword and save the lock? Or should I completely ignore multithreading from the moment I get and set the logical values ​​of the atom?

Yours faithfully,

+7
multithreading
source share
2 answers

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.

+9
source share

volatile is not enough and serves for another purpose, the lock should be fine, but in the end it depends on who is going to install boolVal in MyClass iself, who knows, you can have a workflow spinning there. It also depends on how you use boolVal internally. You may also need protection elsewhere. If you ask me if you are not dead, you are going to use MyClass in more than one thread, then you should not even think about it.

PS you can also read this section

+2
source share

All Articles