Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is int? thread safe?

Tags:

I know that in .Net all 32-bit types (e.g, int, bool, etc) are thread safe. That is, there won't be a partial write (according to the specifications).

But, does the same apply for int? (nullable int)?

like image 753
Jeremy Avatar asked Jun 15 '10 16:06

Jeremy


People also ask

Is reading an int thread-safe?

The proper value will be written atomically as a single operation, and threads will read the current value as a single atomic operation as well, even if another thread is writing. So for integers, you're safe on most architectures.

Is int thread-safe in Java?

6) Atomic operations in Java are thread-safe like reading a 32-bit int from memory because it's an atomic operation it can't interleave with other threads.

Is int thread-safe C++?

A good rule of thumb for choosing behaviour for a class in C++ is "do as int s do". With regard to thread safety, int s are simple: Any number of threads may read a given int concurrently. If any thread modifies a given int , no other threads may access that int for reading or writing concurrently.

Is ++ operator thread-safe in Java?

Example of Non-Thread-Safe Code in Java The above example is not thread-safe because ++ (the increment operator) is not an atomic operation and can be broken down into reading, update, and write operations.


1 Answers

The question is poorly worded, and hence the confusion in the answers so far. The question should be "are reads and writes to a variable of type int? guaranteed to be atomic?"

No, absolutely not. The spec is extremely clear on this point:

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.

It is entirely possible for a thread to read a partially written value from a shared-memory variable of nullable type.

For example, suppose you have an int? variable x which at present has the value null. It therefore contains an int, set to zero, and a bool, set to false. Now on another thread you write the nullable int "5" to x. It is perfectly legal for another thread to read the non-nullable int zero from x, because the "true" in the bool could be set before the 5 is set to the int.

like image 105
Eric Lippert Avatar answered Sep 23 '22 15:09

Eric Lippert