views:

310

answers:

3

I know that in .net any 32bit type (int, bool, etc) are threadsafe. you know that there won't be a partial write ever (according to the spec). Does the same apply for int? (nullable int)

+10  A: 

No, since an int? is actually a struct (Nullable<int>) composed of an int and a bool.

Anton Tykhyy
@Eric: But, excepting conversion operators, there are no public static members on `Nullable<T>`.
LukeH
@LukeH: what does that have to do with the question?
Eric Lippert
@Eric: My comment was in response to an earlier comment (since deleted) made by another Eric, claiming that some members of the `int?` type -- the public static members -- were thread-safe.
LukeH
+3  A: 

From http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Stuart Branham
The problem is that `Nullable<T>` has no public static members (unless you count the conversion operators to/from `T` itself). This is just boilerplate text which you'll find in the documentation for most objects on MSDN.
LukeH
Does the fact that it is common documentation copy make it less accurate?
Stuart Branham
@Stuart ...suspect in the least :)
Rusty
+10  A: 

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.

Eric Lippert
I understand your example for int? .. but why are reads/writes to long, double and decimal not atomic?
MalcomTucker
@MalcomTucker: The 32 bit processor only guarantees that operations on variables are atomic if they are 32 bits. Long, double and decimal can require more than one operation to write or read the whole value because they are larger than 32 bits.
Eric Lippert
@MalcolmTucker: http://msdn.microsoft.com/en-us/library/system.threading.interlocked_members.aspx offers functionality to provide the ability to perform atomic operations on doubles and other types.
Brian