Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net: Is assigning an object reference atomic (i.e. thread-safe)?

Let's say I have some variable x (of type myClass), which is initially null and some assignment

x = myObject

occuring exactly once in some background thread.

Is it guaranteed that x always contains either null or myObject when accessed from the main thread? Or is it possible that x contains some invalid data shortly?

like image 539
Heinzi Avatar asked Feb 26 '10 12:02

Heinzi


2 Answers

Provided the size of the type reference is the same size as the native word size of the CPU, then the assignment will be atomic (and safe in your described scenario).

In fact, (don't have the reference to hand) I'm fairly certain that a type ref will always be the same size as the native CPU word size.

like image 190
Mitch Wheat Avatar answered Oct 13 '22 07:10

Mitch Wheat


From this (although it deals with somewhat different topic) I conclude that assignments are atomc.

like image 45
Anton Gogolev Avatar answered Oct 13 '22 07:10

Anton Gogolev