Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is nullable boolean (bool?) considered thread safe?

As the title says, are nullable booleans (bool?) to be considered atomic in their read/write operations? I made a search through the C# documentation to no avail. I know for a fact that only certain primitive types guarantee atomicity in performing read/write operations, and Bool is one of these types. Of course nullable booleans are a different story; they're objects after all so I would say no but...can someone shed some light on this subject?

like image 580
Carlo Arnaboldi Avatar asked Nov 04 '15 17:11

Carlo Arnaboldi


People also ask

Is bool thread safe?

It's more of a C question then a Rust question. But, no, it's not safe. You should use atomics or mutexes for synchronization.

What is a nullable bool?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

How do you check if a boolean is nullable?

Turns out, you can just do this instead: bool? nullableBool = true; if (nullableBool == true) { // some code... } nullableBool == true will evaluate to false if nullableBool is either false or null , in other words: not true.

Which of these is not a legal value for a nullable bool variable?

Boolean variable cannot have a value of null because it is a non-nullable value type. Answer is 1 & 5. 1) We can assign the any type value to the variable of object data type.


2 Answers

C# does not guarantee that reads and writes of nullable variables are atomic. The types for which operations are guaranteed to be atomic are defined in section 5.5 of the specification (Atomicity of variable references):

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic. Aside from the library functions designed for that purpose, there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement.

Note that while nullables can be null, they are not reference types. They are value types that have special boxing behavior provided by the runtime. In the context of the specification, they are called nullable value types if they require special treatment.

like image 158
Mike Zboray Avatar answered Sep 24 '22 09:09

Mike Zboray


According to Nullable(T):

Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

like image 32
Matias Cicero Avatar answered Sep 24 '22 09:09

Matias Cicero